【问题标题】:how do I get location's latitude and longtitude by address in text [duplicate]如何通过文本中的地址获取位置的纬度和经度[重复]
【发布时间】:2014-09-19 20:12:49
【问题描述】:

我需要得到...例如,伦敦的纬度和经度。
所以我将字符串“伦敦”传递给一个函数,然后该函数返回我纬度和 lng,所以我可以在谷歌地图中将“中心”位置设置为伦敦。

这是我的一段代码:

 function initialize() {
 // i have below line working, as i was passing in lat and lng value directly....
//var latitudeLongtitude = new google.maps.LatLng(centreLatitude, centreLongitude)
 // now i m trying to pass in a string - 'london'  , it is not working....
           

          var latitudeLongtitude = new google.maps.LatLng(getLatLong("London").lat(), getLatLong("London").lng());


            var mapOptions = {
              zoom: zoom,
              center: latitudeLongtitude,
              mapTypeId: mapType
            };

            var map = new google.maps.Map(document.getElementById('map-canvas'),
                mapOptions);

            var marker = new google.maps.Marker({
                position: latitudeLongtitude,
                map: map,
                title: 'Hello World!',
                icon: markersImage
            });
          }
    google.maps.event.addDomListener(window, 'load', initialize);


function getLatLong(address){
        var geo = new google.maps.Geocoder;

        geo.geocode({'address':address},function(results, status){
                if (status == google.maps.GeocoderStatus.OK) {
                  return results[0].geometry.location;
                } else {
                  alert("Geocode was not successful for the following reason: " + status);
                }

         });

    }

基本上,我试图修改基于this example的代码

请任何人都可以帮助我提供代码示例,谢谢.....

【问题讨论】:

  • 您是否有有效的 API 密钥等。Read this 并遵循 TOS
  • 是的....我有一个有价值的 api 密钥
  • 你指的example不正确,地理编码器是asynchronous,回调函数无法返回结果。

标签: javascript google-maps-api-3 geolocation latitude-longitude geo


【解决方案1】:

由于google.maps.Geocoder 是异步方法,您需要在收到响应后调用initialize()

geo.geocode({'address':address},function(results, status){
    if (status == google.maps.GeocoderStatus.OK) {
        initialize( results[0].geometry.location.lat, results[0].geometry.location.lng );
    } else {
        alert("Geocode was not successful for the following reason: " + status);
    }
});

并将您的 initialize() 函数更改为接受 latlng 参数:

function initialize( lat, lng ) {
    var latitudeLongtitude = new google.maps.LatLng( lat, lng );
//....

然后你就可以通过调用来初始化你的地图:

getLatLong( 'London' );

【讨论】:

  • sry...我很困惑....到底是怎么回事?所以我有第一个geo.geocode方法,然后在第二个地方初始化,然后在第三个地方调用getLatLong(地址)?
  • 我把 getLatLong( 'London' ); ?干杯...
  • 你需要把它而不是“initialize()”调用。我不知道你在哪里叫它。可能在body标签或window.load方法中
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-04
相关资源
最近更新 更多