使用Javascript从谷歌地点搜索API获取纬度和经度

42

3
可能是重复的问题:Google Maps获取LatLng值 - geocodezip
可能是Google Places get LatLng的重复问题。 - Chris Moschini
5个回答

64
function GetLatlong() {
  var geocoder = new google.maps.Geocoder();
  var address = document.getElementById('textboxid').value;

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

您可以使用上述函数,该函数将为用户输入的区域提供纬度和经度。


寻找了好几天如何使用人们不断指向使用google.maps.places.placesservice.getPlaceDetails()函数。现在我知道我一直需要的是Geocoder!如果我几天前就找到了这个答案就好了!您可以使用自动完成并为其添加change事件的eventlistener,然后从该列表中获取位置,但是当使用angular应用程序时,这是一个更简单的解决方案。在我看来,这应该被标记为答案。 - James Blackburn

26

您提供的链接上的代码展示了一个在输入搜索时执行的函数。首先,它创建了一个空数组来存储标记(即在执行搜索后在地图上看到的“插针”)。

因此,请检查以以下方式开始的函数:

google.maps.event.addListener(searchBox, 'places_changed', function() {

稍后您将会看到已经创建了一个标记(甚至有一条注释):

// Create a marker for each place.
var marker = new google.maps.Marker({
    map: map,
    icon: image,
    title: place.name,
    position: place.geometry.location
});

因此,在place.geometry.location上,您有一个Google Maps位置对象。 您可以使用place.geometry.location.lat()place.geometry.location.lng()

这里也可以查看: https://dev59.com/8GUp5IYBdhLWcg3wXGy8#15315483


一开始我真的很苦恼,但这个是关键,表述清晰并且在监听器中可用。 - edencorbin

10

以下是来自文档的内容:

// Autocomplete Options
var defaultBounds = new google.maps.LatLngBounds();
var options = {
  types: ['(cities)'],
  bounds: defaultBounds
};

// get DOM's input element
var input = document.getElementById('location_address');

// Make Autocomplete instance
var autocomplete = new google.maps.places.Autocomplete(input, options);

// Listener for whenever input value changes            
autocomplete.addListener('place_changed', function() {

  // Get place info
  var place = autocomplete.getPlace();

  // Do whatever with the value!
  console.log(place.geometry.location.lat());
});

1

HTML:

<input type="text" id="address" name="address" value=""> //Autocomplete input address

<input type="hidden" name="s_latitude" id="s_latitude" value="" /> //get latitude
<input type="hidden" name="s_longitude" id="s_longitude" value="" /> //get longitude

Javascript:

<script src="https://maps.googleapis.com/maps/api/js?key=API_KEY&libraries=places&callback=initMap"
async defer></script>

<script>
var input = document.getElementById('address');
var originLatitude = document.getElementById('s_latitude');
var originLongitude = document.getElementById('s_longitude');

var originAutocomplete = new google.maps.places.Autocomplete(input);

    
originAutocomplete.addListener('place_changed', function(event) {
    var place = originAutocomplete.getPlace();

    if (place.hasOwnProperty('place_id')) {
        if (!place.geometry) {
                // window.alert("Autocomplete's returned place contains no geometry");
                return;
        }
        originLatitude.value = place.geometry.location.lat();
        originLongitude.value = place.geometry.location.lng();
    } else {
        service.textSearch({
                query: place.name
        }, function(results, status) {
            if (status == google.maps.places.PlacesServiceStatus.OK) {
                originLatitude.value = results[0].geometry.location.lat();
                originLongitude.value = results[0].geometry.location.lng();
            }
        });
    }
});
</script>

-3
navigator.geolocation.getCurrentPosition(success => {

  console.log(success) // `have the lat and long`

}, failure =>{

//`enter code here if failed`

});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接