简体   繁体   English

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

[英]Google Maps - using geocoder to get long/lat with javascript

I'm trying to get longitude and latitude values from the google maps api with an address, however it doesn't seem to be returning any value. 我试图从谷歌地图api获取经度和纬度值与地址,但它似乎没有返回任何值。 Is there a problem with my syntax? 我的语法有问题吗?

var point = GClientGeocoder.getLatLng('1600 Pennsylvania Avenue NW Washington, DC 20500');
alert(point);

It seems like you're using v2 of Google Maps; 您似乎正在使用谷歌地图的v2; if you're interested in using v3 (since Google has officially deprecated version 2), you could do something like this: 如果您对使用v3感兴趣(因为Google已正式弃用版本2),您可以执行以下操作:

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

It's similar to the other examples except: 它与其他例子类似,除了:

  • You call new google.maps.Geocoder() instead of GClientGeocoder() 你调用新的google.maps.Geocoder()而不是GClientGeocoder()
  • You pass in an object with an 'address' property, instead of the string by itself 传入一个带有'address'属性的对象,而不是字符串本身
  • The results is a JSON object, which means you have to access lat/lng a little differently 结果是一个JSON对象,这意味着你必须以不同的方式访问lat / lng

The Google API docs have more detail for v3. Google API文档提供了有关v3的更多详细信息。 Cheers! 干杯!

This works (provided you have the correct API key, subject to the 2500 requests/day rate limit): 这有效(前提是您拥有正确的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.
        }
    }
);

You seem to be calling a function of GClientGeocoder , where you need to create a new GClientGeocoder() and call its function. 您似乎在调用GClientGeocoder的函数,您需要在其中创建new GClientGeocoder()并调用函数。

Try it like: 试试吧:

geocoder = new GClientGeocoder();
point = geocoder.getLatLng(address)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM