谷歌地图 - 使用地理编码器通过 javascript 获取长/纬度

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3684765/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 01:56:11  来源:igfitidea点击:

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

javascriptgoogle-maps

提问by Queueball

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. Is there a problem with my syntax?

我正在尝试从带有地址的 google maps api 获取经度和纬度值,但是它似乎没有返回任何值。我的语法有问题吗?

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

采纳答案by Piskvor left the building

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 itsfunction.

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

回答by Christopher Scott

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:

看起来您使用的是 Google Maps v2;如果您对使用 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()
  • You pass in an object with an 'address' property, instead of the string by itself
  • The results is a JSON object, which means you have to access lat/lng a little differently
  • 您调用new google.maps.Geocoder()而不是 GClientGeocoder()
  • 您传入一个具有“地址”属性的对象,而不是字符串本身
  • 结果是一个 JSON 对象,这意味着您必须以稍微不同的方式访问 lat/lng

The Google API docshave more detail for v3. Cheers!

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

回答by Ankit Jaiswal

Try it like:

试试看:

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