谷歌地图api从没有地图的自动完成中获取纬度和经度

MCR*_*CRD 52 autocomplete google-maps-api-3

我试图从自动完成api谷歌地图获取经度和经度而不显示地图.在我的脚本中,自动完成功能很好但我无法获得经度和纬度.

<script type="text/javascript">
   function initialize() {

 var options = {
  types: ['(cities)']
 };

 var input = document.getElementById('searchTextField');
 var autocomplete = new google.maps.places.Autocomplete(input, options);
}
   google.maps.event.addDomListener(window, 'load', initialize);

   var geocoder = new google.maps.Geocoder();
    var address = autocomplete;

geocoder.geocode( { 'address': address}, function(results, status) {

  if (status == google.maps.GeocoderStatus.OK) {
    var latitude = results[0].geometry.location.lat();
    var longitude = results[0].geometry.location.lng();
    alert(latitude);
  } 
}); 

</script>
Run Code Online (Sandbox Code Playgroud)

小智 119

您可以使用以下代码.

<script src="http://maps.googleapis.com/maps/api/js?libraries=places" type="text/javascript"></script>

<script type="text/javascript">
    function initialize() {
        var input = document.getElementById('searchTextField');
        var autocomplete = new google.maps.places.Autocomplete(input);
        google.maps.event.addListener(autocomplete, 'place_changed', function () {
            var place = autocomplete.getPlace();
            document.getElementById('city2').value = place.name;
            document.getElementById('cityLat').value = place.geometry.location.lat();
            document.getElementById('cityLng').value = place.geometry.location.lng();
            //alert("This function is working!");
            //alert(place.name);
           // alert(place.address_components[0].long_name);

        });
    }
    google.maps.event.addDomListener(window, 'load', initialize); 
</script>
Run Code Online (Sandbox Code Playgroud)

这部分在你的表格内:

<input id="searchTextField" type="text" size="50" placeholder="Enter a location" autocomplete="on" runat="server" />  
<input type="hidden" id="city2" name="city2" />
<input type="hidden" id="cityLat" name="cityLat" />
<input type="hidden" id="cityLng" name="cityLng" />  
Run Code Online (Sandbox Code Playgroud)

我希望它有所帮助.


Quy*_* Le 27

只需要:

var place = autocomplete.getPlace();
// get lat
var lat = place.geometry.location.lat();
// get lng
var lng = place.geometry.location.lng();
Run Code Online (Sandbox Code Playgroud)


Aka*_*hal 9

您无法从自动完成 API 获取纬度/经度,因为谷歌从该 API 生成的数据不包含纬度和经度字段。例子:-

{
   "predictions" : [
      {
         "description" : "IIT Mumbai, Mumbai, Maharashtra, India",
         "id" : "ac3235cda973818a89b5fe21ad0f5261ac9b6723",
         "matched_substrings" : [
            {
               "length" : 10,
               "offset" : 0
            }
         ],
         "reference" : "CkQ0AAAAHWg-RSngiYHHdz_yqyFKmfSoBwT-_PW0k8qQDhsbiVrk7BlPHCyJb58OthledMUTGYS5Vhec1Zj2L7w9Rq0zDxIQrbn05RX1QgWHkSXsmTk1TRoU45APW2BBRIUsA3t6XBy_8s0BPPA",
         "terms" : [
            {
               "offset" : 0,
               "value" : "IIT Mumbai"
            },
            {
               "offset" : 12,
               "value" : "Mumbai"
            },
            {
               "offset" : 20,
               "value" : "Maharashtra"
            },
            {
               "offset" : 33,
               "value" : "India"
            }
         ],
         "types" : [ "establishment", "geocode" ]
      }
   ],
   "status" : "OK"
}
Run Code Online (Sandbox Code Playgroud)

您可以使用 Google API 从您的地址获取经度和纬度。正如您已经说过的,您应该在应该插入结果的位置实现一个隐藏字段。然后您可以将位置与坐标一起保存。

例如https://maps.googleapis.com/maps/api/geocode/json?address=IIT%20Area,%20Mumbai,%20Maharashtra,%20India&sensor=false

我最近在我的一个项目中实现了这个功能:

function getLatLngFromAddress(city, country){

  var address = city +", "+ country;
  var geocoder = new google.maps.Geocoder();

  geocoder.geocode( { 'address': address}, function(results, status) {

    if (status == google.maps.GeocoderStatus.OK) {
      $('#latitude').val(results[0].geometry.location.Pa);
      $('#longitude').val(results[0].geometry.location.Qa);

    } else {
      console.log("Geocode was not successful for the following reason: " + status);
    }
  });
}
Run Code Online (Sandbox Code Playgroud)

  • 只需将地点详细信息用于您获得的 place_id https://developers.google.com/places/documentation/details (3认同)
  • place.geometry.location.lat() (3认同)

Val*_*Shi 7

截至 2020 年底,这很简单,如下所示。

对于要geometry在从位置下拉列表中选择的位置上显示的键,应使用方法在对象实例geometry上设置该字段。AutocompletesetFields()

代码应该如下所示。

加载API库:

<script src="https://maps.googleapis.com/maps/api/js?key=API_KEY&libraries=places&callback=initAutocomplete"
Run Code Online (Sandbox Code Playgroud)

初始化自动完成并处理所选地点数据通常与其他答案相同。但用来autocomplete.setFields(['geometry'])取回坐标;

let autocomplete;

// Init the autocomplete object
function initAutocomplete() {
    autocomplete = new window.google.maps.places.Autocomplete(
        document.getElementById('current_location'), { types: ["geocode"] }
    );

    // !!! This is where you set `geometry` field to be returned with the place.
    autocomplete.setFields(['address_component', 'geometry']); // <--

    autocomplete.addListener("place_changed", fillInAddress);
}

// Process the address selected by user
function fillInAddress() {
    const place = autocomplete.getPlace();

    // Here you can get your coordinates like this
    console.log(place.geometry.location.lat());
    console.log(place.geometry.location.lng());
}
Run Code Online (Sandbox Code Playgroud)

Autocomplete.setFields请参阅有关和geometry选项的 Google API 文档。


4nd*_*o1d 5

是的你可以:

var place = autocomplete.getPlace();

document.getElementById('lat').value = place.geometry.location.lat();
document.getElementById('lon').value = place.geometry.location.lng();
Run Code Online (Sandbox Code Playgroud)


小智 5

你可以从地方对象 ie 得到 lat, lng

var place = autocomplete.getPlace();

var latitude = place.geometry.location.lat();
var longitude = place.geometry.location.lng();
Run Code Online (Sandbox Code Playgroud)


wf9*_*m75 1

Google Places API 还提供 REST api,包括地点自动完成。 https://developers.google.com/places/documentation/autocomplete

但从服务检索的数据必须用于地图。

  • 现在看来并非如此。Google API 文档说:“即使没有地图,您也可以使用地点自动完成功能。如果您确实显示地图,则它必须是 Google 地图。当您在没有地图的情况下显示地点自动完成服务的预测时,必须包含‘powered通过谷歌的标志。” 这取自 API 文档:https://developers.google.com/places/documentation/autocomplete (3认同)