谷歌地图: 如何获得国家,州/省/地区,城市给定的 lat/long 值?

我需要一个国家,州和城市的列表,基于我有 lat/long 值的集合。我需要保存这个信息的方式,层次结构是保留和没有重复(例如“美国”和“美国”和“美利坚合众国”是同一个国家; 我只想在我的数据库中这个国家的一个实例)。

这可能与谷歌地图 API 做?

320972 次浏览

你要找的是 反座标化。谷歌通过 Google Geocoding 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[] ...

您还可以选择在 xml 而不是 json 中接收响应,只需在请求 URI 中将 json 替换为 xml:

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

据我所知,Google 也会为地址组件返回相同的名称,特别是像国家名称和城市名称这样的高级别名称。尽管如此,请记住,虽然结果是非常准确的大多数应用程序,您仍然可以找到偶尔的拼写错误或模棱两可的结果。

You have a basic answer here: Get city name using geolocation

但是对于你想要的,我推荐这种方式。

只有在你需要管理区域级别1的情况下,才可以为巴黎、德克萨斯、美国和巴黎、法国的 Ile-de-France 存储不同的东西,并提供一个手动备份:

--

在米甲的方式中有一个问题,那就是它需要第一个结果,而不是一个特定的结果。他使用结果[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>

我用这个问题作为我自己解决方案的出发点。我觉得把我的代码贡献回去是合适的因为它比烟草的小

依赖性:

密码:

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

当我将 GeoCoder javascript 包含在 jsp 文件中时,我发现它有点毛病。

你也可以试试这个:




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


试试这个代码,这个代码对我有用

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

我编写了这个函数,它基于从 gmap 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等等。

In my js code I am using like so:

const location =`${getAddressCity(address_components, 'short')}, ${getAddressState(address_components, 'short')}`

将返回: Waltham, MA

我创建了一个小的 mapper 函数:

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

这是角度4的一个解决方案,但我想你会明白的。

用法:

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"
}

希望能有帮助!

 <div id="location"></div>
<script>
window.onload = function () {
var startPos;
var geoOptions = {
maximumAge: 5 * 60 * 1000,
timeout: 10 * 1000,
enableHighAccuracy: true
}




var geoSuccess = function (position) {
startPos = position;
geocodeLatLng(startPos.coords.latitude, startPos.coords.longitude);


};
var geoError = function (error) {
console.log('Error occurred. Error code: ' + error.code);
// error.code can be:
//   0: unknown error
//   1: permission denied
//   2: position unavailable (error response from location provider)
//   3: timed out
};


navigator.geolocation.getCurrentPosition(geoSuccess, geoError, geoOptions);
};
function geocodeLatLng(lat, lng) {
var geocoder = new google.maps.Geocoder;
var latlng = {lat: parseFloat(lat), lng: parseFloat(lng)};
geocoder.geocode({'location': latlng}, function (results, status) {
if (status === 'OK') {
console.log(results)
if (results[0]) {
document.getElementById('location').innerHTML = results[0].formatted_address;
var street = "";
var city = "";
var state = "";
var country = "";
var zipcode = "";
for (var i = 0; i < results.length; i++) {
if (results[i].types[0] === "locality") {
city = results[i].address_components[0].long_name;
state = results[i].address_components[2].long_name;


}
if (results[i].types[0] === "postal_code" && zipcode == "") {
zipcode = results[i].address_components[0].long_name;


}
if (results[i].types[0] === "country") {
country = results[i].address_components[0].long_name;


}
if (results[i].types[0] === "route" && street == "") {


for (var j = 0; j < 4; j++) {
if (j == 0) {
street = results[i].address_components[j].long_name;
} else {
street += ", " + results[i].address_components[j].long_name;
}
}


}
if (results[i].types[0] === "street_address") {
for (var j = 0; j < 4; j++) {
if (j == 0) {
street = results[i].address_components[j].long_name;
} else {
street += ", " + results[i].address_components[j].long_name;
}
}


}
}
if (zipcode == "") {
if (typeof results[0].address_components[8] !== 'undefined') {
zipcode = results[0].address_components[8].long_name;
}
}
if (country == "") {
if (typeof results[0].address_components[7] !== 'undefined') {
country = results[0].address_components[7].long_name;
}
}
if (state == "") {
if (typeof results[0].address_components[6] !== 'undefined') {
state = results[0].address_components[6].long_name;
}
}
if (city == "") {
if (typeof results[0].address_components[5] !== 'undefined') {
city = results[0].address_components[5].long_name;
}
}


var address = {
"street": street,
"city": city,
"state": state,
"country": country,
"zipcode": zipcode,
};


document.getElementById('location').innerHTML = document.getElementById('location').innerHTML + "<br/>Street : " + address.street + "<br/>City : " + address.city + "<br/>State : " + address.state + "<br/>Country : " + address.country + "<br/>zipcode : " + address.zipcode;
console.log(address);
} else {
window.alert('No results found');
}
} else {
window.alert('Geocoder failed due to: ' + status);
}
});
}
</script>


<script async defer
src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY">
</script>

@ Szk íta 有一个很棒的解决方案,它创建了一个函数来获取命名数组中的地址部分。这里是为那些想要使用普通 JavaScript 的人编译的解决方案。

函数将结果转换为命名数组:

function getAddressParts(obj) {


var address = [];


obj.address_components.forEach( function(el) {
address[el.types[0]] = el.short_name;
});


return address;


} //getAddressParts()

Geocode the LAT/LNG values:

geocoder.geocode( { 'location' : latlng }, function(results, status) {


if (status == google.maps.GeocoderStatus.OK) {
var addressParts =  getAddressParts(results[0]);


// the city
var city = addressParts.locality;


// the state
var state = addressParts.administrative_area_level_1;
}


});

最好首先将 google 对象转换为 javascript 可读对象。

创建两个函数,如下所示,并调用它传递谷歌地图返回对象。

function getShortAddressObject(object) {
let address = {};
const address_components = object[0].address_components;
address_components.forEach(element => {
address[element.types[0]] = element.short_name;
});
return address;
}


function getLongAddressObject(object) {
let address = {};
const address_components = object[0].address_components;
address_components.forEach(element => {
address[element.types[0]] = element.long_name;
});
return address;
}

Then user can access names like below.

var addressObj = getLongAddressObject(object);
var country = addressObj.country; //Sri Lanka

所有地址部分如下。

administrative_area_level_1: "Western Province"
administrative_area_level_2: "Colombo"
country: "Sri Lanka"
locality: "xxxx xxxxx"
political: "xxxxx"
route: "xxxxx - xxxxx Road"
street_number: "No:00000"

这并不复杂,如果你想找一个国家,请看下面的代码:

const latlng = `-8.838333,13.234444`
let url_ = `https://maps.googleapis.com/maps/api/geocode/json?latlng=${latlng}&key=API_KEY&result_type=country`;
$.ajax({
url: url_,
method: "GET",
success: (data)=>{
let country = data.results[data.results.length-1].formatted_address;
console.log(country)
},
error: (e)=>{
console.error(e)
}
})

以下代码是实际检索该国家的代码:

data.results[data.results.length-1].formatted_address

数据数组中的最后一个元素实际上是国家。