谷歌地图:如何得到国家,州/省/地区,城市具有经济价值?
我需要一个国家,州和城市的名单,根据我拥有的纬度/经度值的集合。 我需要将这些信息存储起来,保持层次结构不重复(例如“美国”和“美国”和“美国”是同一个国家;我只希望在我的数据库中有一个这样的国家实例) 。
这可能与Google Map API有关吗?
你正在寻找什么叫反向地理编码 。 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[] ...
你也可以select在xml中接收响应而不是json,只需在请求URI中用json代替xml:
http://maps.googleapis.com/maps/api/geocode/xml?latlng=40.714224,-73.961452&sensor=false
据我所知,Google还会为地址组件返回相同的名称,特别是对于国家名称和城市名称等高级名称。 尽pipe如此,请记住,虽然结果对于大多数应用程序来说是非常准确的,但您仍然可以发现偶尔的拼写错误或模棱两可的结果。
这里有一个基本的答案: 使用地理定位获取城市名称
但是对于你正在寻找的东西,我会推荐这种方式。
只有在您还需要administrative_area_level_1时,才能为巴黎,德克萨斯州,美国和巴黎,法国的法兰西岛等地存储不同的东西,并提供手动回退function:
–
米哈尔的方式有一个问题,那就是第一个结果,而不是特定的结果。 他使用结果[0]。 我认为合适的方式(我只是修改了他的代码)是只采取types为“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 (按名称search/由lat&lngsearch)
这样:同样的获取结果。
<!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 = 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 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>
我用这个问题作为我自己的解决scheme的起点。 认为从小于tabacitu的angular度来回推我的代码是合适的
依赖关系:
- underscore.js
- https://github.com/estebanav/javascript-mobile-desktop-geolocation
- <script src =“https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false”> </ script>
码:
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 }); }
当我将它包含在我的jsp文件中时,我发现GeoCoder javascript有点小问题。
你也可以试试这个:
var lat = "43.7667855" ; var long = "-79.2157321" ; var url = "https://maps.googleapis.com/maps/api/geocode/json?latlng=" +lat+","+long+"&sensor=false"; $.get(url).success(function(data) { var loc1 = data.results[0]; var county, city; $.each(loc1, function(k1,v1) { if (k1 == "address_components") { for (var i = 0; i < v1.length; i++) { for (k2 in v1[i]) { if (k2 == "types") { var types = v1[i][k2]; if (types[0] =="sublocality_level_1") { county = v1[i].long_name; //alert ("county: " + county); } if (types[0] =="locality") { city = v1[i].long_name; //alert ("city: " + city); } } } } } }); $('#city').html(city); });
我写了这个函数,它根据从gmaps API返回的address_components
提取你正在寻找的东西。 这是城市(例如)。
export const getAddressCity = (address, length) => { const findType = type => type.types[0] === "locality" const location = address.map(obj => obj) const rr = location.filter(findType)[0] return ( length === 'short' ? rr.short_name : rr.long_name ) }
将国家locality
更改为administrative_area_level_1
等
在我的js代码中,我使用的是这样的:
const location =`${getAddressCity(address_components, 'short')}, ${getAddressState(address_components, 'short')}`
将返回: Waltham, MA
试试这个代码,这个代码和我一起工作
var posOptions = {timeout: 10000, enableHighAccuracy: false}; $cordovaGeolocation.getCurrentPosition(posOptions).then(function (position) { var lat = position.coords.latitude; var long = position.coords.longitude; //console.log(lat +" "+long); $http.get('https://maps.googleapis.com/maps/api/geocode/json?latlng=' + lat + ',' + long + '&key=your key here').success(function (output) { //console.log( JSON.stringify(output.results[0])); //console.log( JSON.stringify(output.results[0].address_components[4].short_name)); var results = output.results; if (results[0]) { //console.log("results.length= "+results.length); //console.log("hi "+JSON.stringify(results[0],null,4)); for (var j = 0; j < results.length; j++){ //console.log("j= "+j); //console.log(JSON.stringify(results[j],null,4)); for (var i = 0; i < results[j].address_components.length; i++){ if(results[j].address_components[i].types[0] == "country") { //this is the object you are looking for country = results[j].address_components[i]; } } } console.log(country.long_name); console.log(country.short_name); } else { alert("No results found"); console.log("No results found"); } }); }, function (err) { });
我创build了一个小的映射器函数:
private getAddressParts(object): Object { let address = {}; const address_components = object.address_components; address_components.forEach(element => { address[element.types[0]] = element.short_name; }); return address; }
这是Angular 4的解决scheme,但我想你会明白的。
用法:
geocoder.geocode({ 'location' : latlng }, (results, status) => { if (status === google.maps.GeocoderStatus.OK) { const address = { formatted_address: results[0].formatted_address, address_parts: this.getAddressParts(results[0]) }; (....) }
这样的address
对象将是这样的:
address: { address_parts: { administrative_area_level_1: "NY", administrative_area_level_2: "New York County", country: "US", locality: "New York", neighborhood: "Lower Manhattan", political: "Manhattan", postal_code: "10038", route: "Beekman St", street_number: "90", }, formatted_address: "90 Beekman St, New York, NY 10038, USA" }
希望它有帮助!