使用Google地图API填充经度和纬度 [英] Populate the longitude and latitude using google maps API

查看:116
本文介绍了使用Google地图API填充经度和纬度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下html和javascript。 JavaScript从谷歌地图API填充位置详细信息到HTML表单字段。这个想法是有人输入他们的原始位置,它填充在第一个HTML表单域中,然后输入第二个位置,该位置以第二个表单填充。这是完美的。



现在我也想用第一和第二位置的经度和纬度填充表格。

  *<!DOCTYPE html> 
< html>
< head>
< title>放置自动填充地址表单< / title>
< meta name =viewportcontent =initial-scale = 1.0,user-scalable = no>
< meta charset =utf-8>
< link type =text / css =stylesheethref =https://fonts.googleapis.com/css?family=Roboto:300,400,500>
< / head>

< body>
< script src =https://maps.googleapis.com/maps/api/js?libraries=places>< / script>
< div id =locationField>
< input id =autocompleteplaceholder =开始输入您的地址onFocus =geolocate()type =text/>
< / div>
< div id =addressone>
< input type =textid =street_numbername =street_number/>
< input type =textid =routename =street_name/>
< input type =textid =localityname =town_city/>
< input type =textid =administrative_area_level_1name =administrative_area_level_1/>
< input type =textid =postal_codename =postcode/>
< input type =textid =countryname =country/>
< input type =textid =longitudename =longitude/>
< input type =textid =latitudename =latitude/>

< / div>
< div id =locationField2>
< input id =autocomplete2placeholder =开始输入您的地址onFocus =geolocate()type =text/>
< / div>
< div id =addresstwo>
< input type =textid =street_number2name =street_number2/>
< input type =textid =route2name =street_name2/>
< input type =textid =locality2name =town_city2/>
< input type =textid =administrative_area_level_12name =administrative_area_level_12/>
< input type =textid =postal_code2name =postcode2/>
< input type =textid =country2name =country2/>
< input type =textid =longitude2name =longitude2/>
< input type =textid =latitude2name =latitude2/>
< / div>

< script>
//此示例使用Google Places API的自动填充功能
//来显示地址表单,以帮助用户填写信息。

var placeSearch,autocomplete,autocomplete2;
var componentForm = {
street_number:'short_name',
route:'long_name',
locality:'long_name',
administrative_area_level_1:'short_name',
国家:'long_name',
postal_code:'short_name'
};

函数initAutocomplete(){
//创建自动填充对象,将搜索限制为地理区域
//位置类型。
autocomplete = new google.maps.places.Autocomplete(
/ ** @type {!HTMLInputElement} * /
(document.getElementById('autocomplete')),{
类型:['geocode']
});

//当用户从下拉列表中选择一个地址时,填写表单中的地址
//字段。
autocomplete.addListener('place_changed',function(){
fillInAddress(autocomplete,);
});
$ b autocomplete2 = new google.maps.places.Autocomplete(
/ ** @type {!HTMLInputElement} * /
(document.getElementById('autocomplete2')),{
类型:['geocode']
});
autocomplete2.addListener('place_changed',function(){
fillInAddress(autocomplete2,2);
});

}

函数fillInAddress(自动完成,唯一){
//从自动完成对象中获取地点详细信息。
var place = autocomplete.getPlace();

(componentForm中的var组件){
if(!! document.getElementById(component + unique)){
document.getElementById(component + unique).value =' ;
document.getElementById(component + unique).disabled = false;
}
}

//从地点详细信息
//获取地址的每个组成部分,然后填写表单中相应的字段。
for(var i = 0; i< place.address_components.length; i ++){
var addressType = place.address_components [i] .types [0];
if(componentForm [addressType]&& document.getElementById(addressType + unique)){
var val = place.address_components [i] [componentForm [addressType]];
document.getElementById(addressType + unique).value = val;
}
}
}
google.maps.event.addDomListener(window,load,initAutocomplete);

函数geolocate(){
if(navigator.geolocation){
navigator.geolocation.getCurrentPosition(function(position){
var geolocation = {
lat:position.coords.latitude,
lng:position.coords.longitude
};
var circle = new google.maps.Circle({$ b $ center:geolocation,
radius:position.coords.accuracy
});
autocomplete.setBounds(circle.getBounds());
});
}
}
// [END region_geolocation]

< / script>
< script src =https://maps.googleapis.com/maps/api/js?key=AIzaSyAqYwW9d0lnFABF-0NKCTrO__G_d3d958k&signed_in=true&libraries=places&callback=initAutocomplete
async defer> ;< /脚本>
< / body>

代码填充所有必填字段,但不填充经度和纬度。任何解决方法?

解决方案

您没有任何代码来填充纬度和经度字段。添加到 fillInAddress
$ b

  document.getElementById('latitude'+ unique).value = place.geometry.location.lat(); 
document.getElementById('longitude'+ unique).value = place.geometry.location.lng();

完整功能:

 函数fillInAddress(自动完成,唯一){
//从自动完成对象中获取地点详细信息。
var place = autocomplete.getPlace();

(componentForm中的var组件){
if(!! document.getElementById(component + unique)){
document.getElementById(component + unique).value =' ;
document.getElementById(component + unique).disabled = false;
}
}

//从地点详细信息
//获取地址的每个组成部分,然后填写表单中相应的字段。
for(var i = 0; i< place.address_components.length; i ++){
var addressType = place.address_components [i] .types [0];
if(componentForm [addressType]&& document.getElementById(addressType + unique)){
var val = place.address_components [i] [componentForm [addressType]];
document.getElementById(addressType + unique).value = val;
}
}
document.getElementById('latitude'+ unique).value = place.geometry.location.lat();
document.getElementById('longitude'+ unique).value = place.geometry.location.lng();
}

概念证明小提琴



代码段:

  //此示例显示一个地址表单,使用Google Places API的自动完成功能来帮助用户填写information.var placeSearch,autocomplete,autocomplete2; var componentForm = {street_number:'short_name',route:'long_name',locality:'long_name',administrative_area_level_1:'short_name',country:'long_name',postal_code:'short_name'}; function initAutocomplete(){//创建自动完成对象,限制搜索到地理位置类型。 autocomplete = new google.maps.places.Autocomplete(/ ** @type {!HTMLInputElement} * /(document.getElementById('autocomplete')),{types:['geocode']}); //当用户从下拉列表中选择一个地址时,填写表单中的地址字段。 autocomplete.addListener('place_changed',function(){fillInAddress(autocomplete,);}); autocomplete2 = new google.maps.places.Autocomplete(/ ** @type {!HTMLInputElement} * /(document.getElementById('autocomplete2')),{types:['geocode']}); autocomplete2.addListener('place_changed',function(){fillInAddress(autocomplete2,2);});}函数fillInAddress(autocomplete,unique){//从自动填充对象获取地点详细信息。 var place = autocomplete.getPlace();对于(componentForm中的var组件){if(!! document.getElementById(component + unique)){document.getElementById(component + unique).value =''; document.getElementById(component + unique).disabled = false; }} //从地点详细信息中获取地址的每个组成部分//并填充表单上的相应字段。 for(var i = 0; i< place.address_components.length; i ++){var addressType = place.address_components [i] .types [0]; if(componentForm [addressType]&& document.getElementById(addressType + unique)){var val = place.address_components [i] [componentForm [addressType]]; document.getElementById(addressType + unique).value = val; }} document.getElementById('latitude'+ unique).value = place.geometry.location.lat(); document.getElementById('longitude'+ unique).value = place.geometry.location.lng();} google.maps.event.addDomListener(window,load,initAutocomplete);函数geolocate(){if(navigator。地理位置){navigator.geolocation.getCurrentPosition(function(position){var geolocation = {lat:position.coords.latitude,lng:position.coords.longitude}; var circle = new google.maps.Circle({center:geolocation, radius:position.coords.accuracy}); autocomplete.setBounds(circle.getBounds());}); }} // [END region_geolocation]  

< script src =https://maps.googleapis.com/maps/api/js?libraries=places>< / script>< div id =locationField> < input id =autocompleteplaceholder =开始输入您的地址onFocus =geolocate()type =text/>< / div>< div id =addressone> < input type =textid =street_numbername =street_number/> < input type =textid =routename =street_name/> < input type =textid =localityname =town_city/> < input type =textid =administrative_area_level_1name =administrative_area_level_1/> < input type =textid =postal_codename =postcode/> < input type =textid =countryname =country/> < input type =textid =longitudename =longitude/> < input type =textid =latitudename =latitude/>< / div>< div id =locationField2> < input id =autocomplete2placeholder =开始输入您的地址onFocus =geolocate()type =text/>< / div>< div id =addresstwo> < input type =textid =street_number2name =street_number2/> < input type =textid =route2name =street_name2/> < input type =textid =locality2name =town_city2/> < input type =textid =administrative_area_level_12name =administrative_area_level_12/> < input type =textid =postal_code2name =postcode2/> < input type =textid =country2name =country2/> < input type =textid =longitude2name =longitude2/> < input type =textid =latitude2name =latitude2/>< / div>

p>

I have the following html and javascript. The javascript populates location details from the google maps api to the html form fields. The idea is someone to enter their original location which is populated in the first html form fields and then enter a second location that is populated in the second form. This works perfectly.

Now I also want to populate the form with the longitude and latitude of the first and second locations.

*<!DOCTYPE html>
<html>
  <head>
    <title>Place Autocomplete Address Form</title>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <link type="text/css" rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500">
  </head>

  <body>
    <script src="https://maps.googleapis.com/maps/api/js?libraries=places"></script>
<div id="locationField">
  <input id="autocomplete" placeholder="Start typing your address" onFocus="geolocate()" type="text" />
</div>
<div id="addressone">
  <input type="text" id="street_number" name="street_number" />
  <input type="text" id="route" name="street_name" />
  <input type="text" id="locality" name="town_city" />
  <input type="text" id="administrative_area_level_1" name="administrative_area_level_1" />
  <input type="text" id="postal_code" name="postcode" />
  <input type="text" id="country" name="country" />
  <input type="text" id="longitude" name="longitude" />
  <input type="text" id="latitude" name="latitude" />

</div>
<div id="locationField2">
  <input id="autocomplete2" placeholder="Start typing your address" onFocus="geolocate()" type="text" />
</div>
<div id="addresstwo">
  <input type="text" id="street_number2" name="street_number2" />
  <input type="text" id="route2" name="street_name2" />
  <input type="text" id="locality2" name="town_city2" />
  <input type="text" id="administrative_area_level_12" name="administrative_area_level_12" />
  <input type="text" id="postal_code2" name="postcode2" />
  <input type="text" id="country2" name="country2" />
  <input type="text" id="longitude2" name="longitude2" />
  <input type="text" id="latitude2" name="latitude2" />
</div>

    <script>
// This example displays an address form, using the autocomplete feature
// of the Google Places API to help users fill in the information.

var placeSearch, autocomplete, autocomplete2;
var componentForm = {
  street_number: 'short_name',
  route: 'long_name',
  locality: 'long_name',
  administrative_area_level_1: 'short_name',
  country: 'long_name',
  postal_code: 'short_name'
};

function initAutocomplete() {
  // Create the autocomplete object, restricting the search to geographical
  // location types.
  autocomplete = new google.maps.places.Autocomplete(
    /** @type {!HTMLInputElement} */
    (document.getElementById('autocomplete')), {
      types: ['geocode']
    });

  // When the user selects an address from the dropdown, populate the address
  // fields in the form.
  autocomplete.addListener('place_changed', function() {
    fillInAddress(autocomplete, "");
  });

  autocomplete2 = new google.maps.places.Autocomplete(
    /** @type {!HTMLInputElement} */
    (document.getElementById('autocomplete2')), {
      types: ['geocode']
    });
  autocomplete2.addListener('place_changed', function() {
    fillInAddress(autocomplete2, "2");
  });

}

function fillInAddress(autocomplete, unique) {
  // Get the place details from the autocomplete object.
  var place = autocomplete.getPlace();

  for (var component in componentForm) {
    if (!!document.getElementById(component + unique)) {
      document.getElementById(component + unique).value = '';
      document.getElementById(component + unique).disabled = false;
    }
  }

  // Get each component of the address from the place details
  // and fill the corresponding field on the form.
  for (var i = 0; i < place.address_components.length; i++) {
    var addressType = place.address_components[i].types[0];
    if (componentForm[addressType] && document.getElementById(addressType + unique)) {
      var val = place.address_components[i][componentForm[addressType]];
      document.getElementById(addressType + unique).value = val;
    }
  }
}
google.maps.event.addDomListener(window, "load", initAutocomplete);

function geolocate() {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(position) {
      var geolocation = {
        lat: position.coords.latitude,
        lng: position.coords.longitude
      };
      var circle = new google.maps.Circle({
        center: geolocation,
        radius: position.coords.accuracy
      });
      autocomplete.setBounds(circle.getBounds());
    });
  }
}
// [END region_geolocation]

    </script>
    <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAqYwW9d0lnFABF-0NKCTrO__G_d3d958k&signed_in=true&libraries=places&callback=initAutocomplete"
        async defer></script>
  </body>
</html>*

The code populates all the required fields but does not populate the longitude and latitude. Any work around?

解决方案

You don't have any code to populate the latitude and longitude fields. Add this to fillInAddress:

document.getElementById('latitude'+unique).value = place.geometry.location.lat();
document.getElementById('longitude'+unique).value = place.geometry.location.lng();

complete function:

function fillInAddress(autocomplete, unique) {
  // Get the place details from the autocomplete object.
  var place = autocomplete.getPlace();

  for (var component in componentForm) {
    if (!!document.getElementById(component + unique)) {
      document.getElementById(component + unique).value = '';
      document.getElementById(component + unique).disabled = false;
    }
  }

  // Get each component of the address from the place details
  // and fill the corresponding field on the form.
  for (var i = 0; i < place.address_components.length; i++) {
    var addressType = place.address_components[i].types[0];
    if (componentForm[addressType] && document.getElementById(addressType + unique)) {
      var val = place.address_components[i][componentForm[addressType]];
      document.getElementById(addressType + unique).value = val;
    }
  }
  document.getElementById('latitude'+unique).value = place.geometry.location.lat();
  document.getElementById('longitude'+unique).value = place.geometry.location.lng();
}

proof of concept fiddle

code snippet:

// This example displays an address form, using the autocomplete feature
// of the Google Places API to help users fill in the information.

var placeSearch, autocomplete, autocomplete2;
var componentForm = {
  street_number: 'short_name',
  route: 'long_name',
  locality: 'long_name',
  administrative_area_level_1: 'short_name',
  country: 'long_name',
  postal_code: 'short_name'
};

function initAutocomplete() {
  // Create the autocomplete object, restricting the search to geographical
  // location types.
  autocomplete = new google.maps.places.Autocomplete(
    /** @type {!HTMLInputElement} */
    (document.getElementById('autocomplete')), {
      types: ['geocode']
    });

  // When the user selects an address from the dropdown, populate the address
  // fields in the form.
  autocomplete.addListener('place_changed', function() {
    fillInAddress(autocomplete, "");
  });

  autocomplete2 = new google.maps.places.Autocomplete(
    /** @type {!HTMLInputElement} */
    (document.getElementById('autocomplete2')), {
      types: ['geocode']
    });
  autocomplete2.addListener('place_changed', function() {
    fillInAddress(autocomplete2, "2");
  });

}

function fillInAddress(autocomplete, unique) {
  // Get the place details from the autocomplete object.
  var place = autocomplete.getPlace();

  for (var component in componentForm) {
    if (!!document.getElementById(component + unique)) {
      document.getElementById(component + unique).value = '';
      document.getElementById(component + unique).disabled = false;
    }
  }

  // Get each component of the address from the place details
  // and fill the corresponding field on the form.
  for (var i = 0; i < place.address_components.length; i++) {
    var addressType = place.address_components[i].types[0];
    if (componentForm[addressType] && document.getElementById(addressType + unique)) {
      var val = place.address_components[i][componentForm[addressType]];
      document.getElementById(addressType + unique).value = val;
    }
  }
  document.getElementById('latitude' + unique).value = place.geometry.location.lat();
  document.getElementById('longitude' + unique).value = place.geometry.location.lng();

}
google.maps.event.addDomListener(window, "load", initAutocomplete);

function geolocate() {
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(function(position) {
        var geolocation = {
          lat: position.coords.latitude,
          lng: position.coords.longitude
        };
        var circle = new google.maps.Circle({
          center: geolocation,
          radius: position.coords.accuracy
        });
        autocomplete.setBounds(circle.getBounds());
      });
    }
  }
  // [END region_geolocation]

<script src="https://maps.googleapis.com/maps/api/js?libraries=places"></script>
<div id="locationField">
  <input id="autocomplete" placeholder="Start typing your address" onFocus="geolocate()" type="text" />
</div>
<div id="addressone">
  <input type="text" id="street_number" name="street_number" />
  <input type="text" id="route" name="street_name" />
  <input type="text" id="locality" name="town_city" />
  <input type="text" id="administrative_area_level_1" name="administrative_area_level_1" />
  <input type="text" id="postal_code" name="postcode" />
  <input type="text" id="country" name="country" />
  <input type="text" id="longitude" name="longitude" />
  <input type="text" id="latitude" name="latitude" />

</div>
<div id="locationField2">
  <input id="autocomplete2" placeholder="Start typing your address" onFocus="geolocate()" type="text" />
</div>
<div id="addresstwo">
  <input type="text" id="street_number2" name="street_number2" />
  <input type="text" id="route2" name="street_name2" />
  <input type="text" id="locality2" name="town_city2" />
  <input type="text" id="administrative_area_level_12" name="administrative_area_level_12" />
  <input type="text" id="postal_code2" name="postcode2" />
  <input type="text" id="country2" name="country2" />
  <input type="text" id="longitude2" name="longitude2" />
  <input type="text" id="latitude2" name="latitude2" />
</div>

这篇关于使用Google地图API填充经度和纬度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆