Javascript Google Maps API - 如何在不显示地图的情况下从自动完成获取纬度和经度?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13478646/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 12:11:26  来源:igfitidea点击:

Google Maps API - how to get latitude and longitude from Autocomplete without showing the map?

javascriptgoogle-maps-api-3autocompletelatitude-longitude

提问by MCRD

I'm trying to get latitude and longitude from Autocomplete Google Maps API without showing the map. In my script autocompletion works well, but I can't get the latitude and longitude.

我正在尝试从 Autocomplete Google Maps 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>

回答by Aysegul

You can use the code below.

您可以使用下面的代码。

<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>

and this part is inside your form:

这部分在您的表单中:

<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" />  

I hope it helps.

我希望它有帮助。

回答by Quy Le

Only need:

只需要:

var place = autocomplete.getPlace();
// get lat
var lat = place.geometry.location.lat();
// get lng
var lng = place.geometry.location.lng();

回答by Akash Deep Singhal

You can't get latitude/longitude from autocomplete API since the data generated by google from that API doesn't contain latitude and logitude field. Example:-

您无法从自动完成 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"
}

You can use the Google API to get the Longitude and Latitude from your address. As you already said, you should implement a hidden field where the result should be inserted. Then you can save the location together with the coordinates.

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

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

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

I recently implemented this function in one of my projects:

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

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);
    }
  });
}

回答by cotewa

You can get lat, lng from the place object i.e.

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

var place = autocomplete.getPlace();

var latitude = place.geometry.location.lat();
var longitude = place.geometry.location.lng();

回答by 4ndro1d

Yes you can:

是的你可以:

var place = autocomplete.getPlace();

document.getElementById('lat').value = place.geometry.location.lat();
document.getElementById('lon').value = place.geometry.location.lng();

回答by David Addoteye

You can get from the same api without any additional api or url call.

您可以从同一个 api 获取,而无需任何额外的 api 或 url 调用。

HTML

HTML

<input class="wd100" id="fromInput" type="text" name="grFrom" placeholder="From" required/>

Javascript

Javascript

var input = document.getElementById('fromInput');
var defaultBounds = new google.maps.LatLngBounds(
    new google.maps.LatLng(-33.8902, 151.1759),
    new google.maps.LatLng(-33.8474, 1512631)
)

var options = {
bounds: defaultBounds   
}

var autocomplete = new google.maps.places.Autocomplete(input, options);
var searchBox = new google.maps.places.SearchBox(input, {
         bounds: defaultBounds
});


google.maps.event.addListener(searchBox, 'places_changed', function() {
    var places = searchBox.getPlaces();


console.log(places[0].geometry.location.G); // Get Latitude
console.log(places[0].geometry.location.K); // Get Longitude

//Additional information
console.log(places[0].formatted_address); // Formated Address of Place
console.log(places[0].name); // Name of Place






    if (places.length == 0) {
      return;
    }

    var bounds = new google.maps.LatLngBounds();
    console.log(bounds);
     });
   }

回答by wf9a5m75

Google Places API also provides REST api including Places Autocomplete. https://developers.google.com/places/documentation/autocomplete

Google Places API 还提供 REST api,包括 Places Autocomplete。 https://developers.google.com/places/documentation/autocomplete

But the data retrieve from the service must use for a map.

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