【问题标题】:How to extract latitude and longitude from Google Maps autocomplete如何从谷歌地图自动完成中提取纬度和经度
【发布时间】:2012-02-27 17:11:09
【问题描述】:

我正在构建一个使用此代码搜索地址的网络应用程序:

http://code.google.com/intl/en/apis/maps/documentation/javascript/examples/places-autocomplete.html

在那里输入,纽约,纽约。

因此,当用户在使用自动完成选项后将地图加载到 DOM 中时,用户可以将位置地址保存在数据库中,并且可以使用“ex. New York, NY”。但是,对于应用程序,我还需要保存纬度和经度。

但我不知道如何从 Google API 中获取它们。

作为一个测试应用,我仍在使用谷歌代码。 我想我应该创建一些隐藏字段,并在用户选择地址时为其分配纬度和经度。

欢迎对我的问题进行任何实施!

提前致谢

附注: 由于我是 StackOverflow 的新手,我无法回答自己。 因此,我正在按照 stackoverflow 的建议编辑帖子,这是基于 Daniel 的回答和 Google Api 中的一些研究的解决方案:

function getLatLng( address ) 
{
    var geocoder = new google.maps.Geocoder();
    geocoder.geocode( { 'address' : address }, function( results, status ) {
        if ( status == google.maps.GeocoderStatus.OK ) {
            var mapLatLng = document.getElementById( 'mapLatLng' ); // mapLatLng is my hidden field, use your own
            mapLatLng.value = results[0].geometry.location.lat() + ', ' + results[0].geometry.location.lng();
        } else {
            alert( "Geocode was not successful for the following reason: " + status );
        }

    });            
}

【问题讨论】:

    标签: google-maps latitude-longitude


    【解决方案1】:

    Daniel 在很大程度上是对的,他不正确的地方是他对这里财产的访问:

    $('#latitude').val(results[0].geometry.location.Pa)
    $('#longitude').val(results[0].geometry.location.Qa)
    

    您应该改用提供的 lat() 和 lng() 函数:

    $('#latitude').val(results[0].geometry.location.lat())
    $('#longitude').val(results[0].geometry.location.lng())
    

    【讨论】:

      【解决方案2】:

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

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

      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.lat());
            $('#longitude').val(results[0].geometry.location.lng());
      
          } else {
            console.log("Geocode was not successful for the following reason: " + status);
          }
        });
      }
      

      【讨论】:

        猜你喜欢
        • 2012-06-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-02-18
        • 1970-01-01
        相关资源
        最近更新 更多