谷歌地图:如何获得国家,州/省/地区,城市给出纬度/经度值?

Sta*_*bie 106 google-maps geocoding geolocation google-maps-api-3

我需要一个基于我所拥有的纬度/经度值的集合的国家,州和城市列表.我需要以保持层次结构并且没有重复的方式存储此信息(例如"USA"和"United States"和"United States of America"是同一个国家;我只想在我的数据库中有一个这个国家的实例) .

这可能与Google Map API有关吗?

Dan*_*llo 132

您正在寻找的是反向地理编码.Google通过Google地理编码API提供服务器端反向地理编码服务,您应该可以将其用于您的项目.

这是对以下请求的响应如下:

http://maps.googleapis.com/maps/api/geocode/json?latlng=40.714224,-73.961452&sensor=false

响应:

{
  "status": "OK",
  "results": [ {
    "types": [ "street_address" ],
    "formatted_address": "275-291 Bedford Ave, Brooklyn, NY 11211, USA",
    "address_components": [ {
      "long_name": "275-291",
      "short_name": "275-291",
      "types": [ "street_number" ]
    }, {
      "long_name": "Bedford Ave",
      "short_name": "Bedford Ave",
      "types": [ "route" ]
    }, {
      "long_name": "New York",
      "short_name": "New York",
      "types": [ "locality", "political" ]
    }, {
      "long_name": "Brooklyn",
      "short_name": "Brooklyn",
      "types": [ "administrative_area_level_3", "political" ]
    }, {
      "long_name": "Kings",
      "short_name": "Kings",
      "types": [ "administrative_area_level_2", "political" ]
    }, {
      "long_name": "New York",
      "short_name": "NY",
      "types": [ "administrative_area_level_1", "political" ]
    }, {
      "long_name": "United States",
      "short_name": "US",
      "types": [ "country", "political" ]
    }, {
      "long_name": "11211",
      "short_name": "11211",
      "types": [ "postal_code" ]
    } ],
    "geometry": {
      "location": {
        "lat": 40.7142298,
        "lng": -73.9614669
      },
      "location_type": "RANGE_INTERPOLATED",
      "viewport": {
        "southwest": {
          "lat": 40.7110822,
          "lng": -73.9646145
        },
        "northeast": {
          "lat": 40.7173774,
          "lng": -73.9583193
        }
      }
    }
  },

  ... Additional results[] ...
Run Code Online (Sandbox Code Playgroud)

你也可以选择在xml而不是json中接收响应,只需在请求URI中用json替换xml:

http://maps.googleapis.com/maps/api/geocode/xml?latlng=40.714224,-73.961452&sensor=false

据我所知,谷歌还将为地址组件返回相同的名称,特别是对于国家名称和城市名称等高级别名称.不过,请记住,虽然结果对于大多数应用程序来说非常准确,但您仍然可以发现偶尔的拼写错误或模糊结果.

  • `sensor = false`做什么? (4认同)
  • @StackOverflowNewbie:您可能想要对所有经纬度进行反向地理编码,并在数据库中填写“城市”、“州”、“国家”字段。然后只需对数据库中的这些字段进行过滤。 (2认同)

tab*_*itu 21

您有一个基本答案: 使用地理位置获取城市名称

但是对于你正在寻找的东西,我会推荐这种方式.

只有当您还需要administrative_area_level_1时,才能为巴黎,德克萨斯,美国和巴黎,法兰西岛,法国存储不同的东西,并提供手动后备:

-

Michal的方式存在一个问题,因为它取得了第一个结果,而不是特定结果.他使用结果[0].我认为合适的方式(我只是修改了他的代码)是仅采用其类型为"locality"的结果,即使在浏览器不支持地理定位的情况下最终手动回退的情况下也是如此.

他的方式:获取结果与使用 http://maps.googleapis.com/maps/api/geocode/json?address=bucharest&sensor=false 不同于使用 http://maps.googleapis.com/maps/api/geocode /json?latlng=44.42514,26.10540&sensor=false (按名称搜索/按lat&lng搜索)

这样:获得相同的结果.

<!DOCTYPE html> 
<html> 
<head> 
<meta name="viewport" content="initial-scale=1.0, user-scalable=no"/> 
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/> 
<title>Reverse Geocoding</title> 

<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script> 
<script type="text/javascript"> 
  var geocoder;

  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(successFunction, errorFunction);
} 
//Get the latitude and the longitude;
function successFunction(position) {
    var lat = position.coords.latitude;
    var lng = position.coords.longitude;
    codeLatLng(lat, lng)
}

function errorFunction(){
    alert("Geocoder failed");
}

  function initialize() {
    geocoder = new google.maps.Geocoder();



  }

  function codeLatLng(lat, lng) {

    var latlng = new google.maps.LatLng(lat, lng);
    geocoder.geocode({'latLng': latlng}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
      //console.log(results);
        if (results[1]) {
        var indice=0;
        for (var j=0; j<results.length; j++)
        {
            if (results[j].types[0]=='locality')
                {
                    indice=j;
                    break;
                }
            }
        alert('The good number is: '+j);
        console.log(results[j]);
        for (var i=0; i<results[j].address_components.length; i++)
            {
                if (results[j].address_components[i].types[0] == "locality") {
                        //this is the object you are looking for City
                        city = results[j].address_components[i];
                    }
                if (results[j].address_components[i].types[0] == "administrative_area_level_1") {
                        //this is the object you are looking for State
                        region = results[j].address_components[i];
                    }
                if (results[j].address_components[i].types[0] == "country") {
                        //this is the object you are looking for
                        country = results[j].address_components[i];
                    }
            }

            //city data
            alert(city.long_name + " || " + region.long_name + " || " + country.short_name)


            } else {
              alert("No results found");
            }
        //}
      } else {
        alert("Geocoder failed due to: " + status);
      }
    });
  }
</script> 
</head> 
<body onload="initialize()"> 

</body> 
</html> 
Run Code Online (Sandbox Code Playgroud)


mko*_*yak 6

我使用这个问题作为我自己解决方案的起点。认为将我的代码贡献回来是合适的,因为它比 tabacitu 的小

依赖项:

代码:

if(geoPosition.init()){  

    var foundLocation = function(city, state, country, lat, lon){
        //do stuff with your location! any of the first 3 args may be null
        console.log(arguments);
    }

    var geocoder = new google.maps.Geocoder(); 
    geoPosition.getCurrentPosition(function(r){
        var findResult = function(results, name){
            var result =  _.find(results, function(obj){
                return obj.types[0] == name && obj.types[1] == "political";
            });
            return result ? result.short_name : null;
        };
        geocoder.geocode({'latLng': new google.maps.LatLng(r.coords.latitude, r.coords.longitude)}, function(results, status) {
            if (status == google.maps.GeocoderStatus.OK && results.length) {
                results = results[0].address_components;
                var city = findResult(results, "locality");
                var state = findResult(results, "administrative_area_level_1");
                var country = findResult(results, "country");
                foundLocation(city, state, country, r.coords.latitude, r.coords.longitude);
            } else {
                foundLocation(null, null, null, r.coords.latitude, r.coords.longitude);
            }
        });
    }, { enableHighAccuracy:false, maximumAge: 1000 * 60 * 1 });
}
Run Code Online (Sandbox Code Playgroud)