Google地图 - 使用地理编码器通过javascript获取长/ lat

Que*_*all 8 javascript google-maps

我试图从谷歌地图api获取经度和纬度值与地址,但它似乎没有返回任何值.我的语法有问题吗?

var point = GClientGeocoder.getLatLng('1600 Pennsylvania Avenue NW Washington, DC 20500');
alert(point);
Run Code Online (Sandbox Code Playgroud)

Chr*_*ott 38

It seems like you're using v2 of Google Maps; if you're interested in using v3 (since Google has officially deprecated version 2), you could do something like this:

var mygc = new google.maps.Geocoder();
mygc.geocode({'address' : '1600 Pennsylvania Avenue NW Washington, DC 20500'}, function(results, status){
    console.log( "latitude : " + results[0].geometry.location.lat() );
    console.log( "longitude : " + results[0].geometry.location.lng() );
});
Run Code Online (Sandbox Code Playgroud)

It's similar to the other examples except:

  • You call new google.maps.Geocoder() instead of GClientGeocoder()
  • You pass in an object with an 'address' property, instead of the string by itself
  • 结果是一个JSON对象,这意味着你必须以不同的方式访问lat/lng

谷歌API文档有V3的更多细节.干杯!


Pis*_*3.0 8

这有效(前提是您拥有正确的API密钥,受限于2500个请求/天的速率限制):

address_string = '1600 Pennsylvania Avenue NW Washington, DC 20500';
geocoder = new GClientGeocoder();
geocoder.getLatLng(
    address_string,
    function(point) {
        if (point !== null) {
            alert(point); // or do whatever else with it
        } else {
            // error - not found, over limit, etc.
        }
    }
);
Run Code Online (Sandbox Code Playgroud)

您似乎正在调用函数GClientGeocoder,您需要在其中创建new GClientGeocoder()并调用函数.