<p><button onclick="getLocation()">Get My Location</button></p>
<p id="demo"></p>
<script src="http://maps.google.com/maps/api/js?key=YOUR_API_KEY"></script>
SCRIPT
var x=document.getElementById("demo");
function getLocation(){
if (navigator.geolocation){
navigator.geolocation.getCurrentPosition(showPosition,showError);
}
else{
x.innerHTML="Geolocation is not supported by this browser.";
}
}
function showPosition(position){
lat=position.coords.latitude;
lon=position.coords.longitude;
displayLocation(lat,lon);
}
function showError(error){
switch(error.code){
case error.PERMISSION_DENIED:
x.innerHTML="User denied the request for Geolocation."
break;
case error.POSITION_UNAVAILABLE:
x.innerHTML="Location information is unavailable."
break;
case error.TIMEOUT:
x.innerHTML="The request to get user location timed out."
break;
case error.UNKNOWN_ERROR:
x.innerHTML="An unknown error occurred."
break;
}
}
function displayLocation(latitude,longitude){
var geocoder;
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(latitude, longitude);
geocoder.geocode(
{'latLng': latlng},
function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
var add= results[0].formatted_address ;
var value=add.split(",");
count=value.length;
country=value[count-1];
state=value[count-2];
city=value[count-3];
x.innerHTML = "city name is: " + city;
}
else {
x.innerHTML = "address not found";
}
}
else {
x.innerHTML = "Geocoder failed due to: " + status;
}
}
);
}
if (results[0]) {
var add= results[0].formatted_address ;
var value=add.split(",");
count=value.length;
country=value[count-1];
state=value[count-2];
city=value[count-3];
x.innerHTML = "city name is: " + city;
}
只需控制结果数组
if (results[0]) {
console.log(results[0]);
// choose from console whatever you need.
var city = results[0].address_components[3].short_name;
x.innerHTML = "city name is: " + city;
}
7 回答
这被称为 Reverse Geocoding
http://code.google.com/apis/maps/documentation/geocoding/#ReverseGeocoding .
http://maps.googleapis.com/maps/api/geocode/json?latlng=40.714224,-73.961452&sensor=true
Here is a complete sample:
这是一个使用承诺的现代解决方案:
并称之为:
promise返回'then'中的地址对象或'catch'中的错误状态代码
这是 Google's geocode Web Service 的最新样本
https://maps.googleapis.com/maps/api/geocode/json?latlng=40.714224,-73.961452&key=YOUR_API_KEY
只需将
YOUR_API_KEY
更改为您从Google Geocoding API获得的API密钥P / S: Geocoding API 低于 Places NOT Maps ;)
以下代码正常工作以获取城市名称(使用 Google Map Geo API ):
HTML
SCRIPT
在node.js中,我们可以使用 node-geocoder npm模块从lat,lng . 获取地址,
geo.js
output:
和@Sanchit Gupta一样 .
在这一部分
只需控制结果数组