从邮政编码中获取LatLng - Google Maps API

Sco*_*ott 63 javascript google-maps-api-3

我想要的只是一些简单的示例代码,它向我展示了如何从输入的邮政编码或城市/州获得latlng元素.

Mar*_*ark 89

你不能只用下面的邮政编码或城市和国家调用{zipcode}来调用 http://maps.googleapis.com/maps/api/geocode/json?address= {zipcode}

谷歌地理编码

这是一个使用JavaScript的如何地理编码的链接:Geocode walk-thru.如果需要特定的lat/lng数字,请调用geometry.location.lat()或geometry.location.lng()(google.maps.LatLng类的API)

获取lat/lng的示例:

    var lat = '';
    var lng = '';
    var address = {zipcode} or {city and state};
    geocoder.geocode( { 'address': address}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
         lat = results[0].geometry.location.lat();
         lng = results[0].geometry.location.lng();
        });
      } else {
        alert("Geocode was not successful for the following reason: " + status);
      }
    });
    alert('Latitude: ' + lat + ' Logitude: ' + lng);
Run Code Online (Sandbox Code Playgroud)

  • 这并没有错,但有时即使谷歌地图网站也没有得到一些地方,对我有用的方式是:而不是这个 { 'address': zipcode} 我像这样替换 { 'address': 'zipcode '+ zipcode },我只是在邮政编码之前添加了字符串 'zipcode ',效果更好。 (2认同)

and*_*abs 14

只是一个提示:邮政编码不是全球唯一的,所以在请求中提供国家ISO代码是值得的(https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2).

例如,寻找波兰(iso code PL)zipcode的坐标01-210:

https://maps.googleapis.com/maps/api/geocode/json?address=01210,PL

如何获取用户国家代码?

如果您想获得基于IP地址的用户国家/地区信息,可以为其提供服务,例如您可以通过以下网址进行GET请求:http: //ip-api.com/json


Ram*_*tan 7

这是从邮政编码(即邮政编码)获取经纬度的最可靠方法:

https://maps.googleapis.com/maps/api/geocode/json?key=YOUR_API_KEY&components=postal_code:97403
Run Code Online (Sandbox Code Playgroud)

  • 具有引用限制的 API 密钥不能与此 API 一起使用。 (3认同)

Geo*_*ago 5

这只是对之前答案的改进,因为它对某些邮政编码不起作用,即使在https://www.google.com/maps中也是如此,我修复了在前面添加单词“邮政编码”以将邮政编码,像这样:

function getLatLngByZipcode(zipcode) 
{
    var geocoder = new google.maps.Geocoder();
    var address = zipcode;
    geocoder.geocode({ 'address': 'zipcode '+address }, function (results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            var latitude = results[0].geometry.location.lat();
            var longitude = results[0].geometry.location.lng();
            alert("Latitude: " + latitude + "\nLongitude: " + longitude);
        } else {
            alert("Request failed.")
        }
    });
    return [latitude, longitude];
}
Run Code Online (Sandbox Code Playgroud)


Nar*_*wat 5

在从事实习项目时,我找到了一个网站 https://thezipcodes.com/创建 一个免费帐户并从帐户部分获取 API 密钥。

https://thezipcodes.com/api/v1/search?zipCode={zipCode}&countryCode={2digitCountryCode}&apiKey={apiKey}
Run Code Online (Sandbox Code Playgroud)

我在这里找到了大部分数据。