如何从经纬度得到城市名称?
有没有一种方法来获取经纬度使用谷歌地图API的JavaScript的城市名称?
如果可以,我可以看一个例子吗?
这被称为反向地理编码
这是一个完整的示例:
<!DOCTYPE html> <html> <head> <title>Geolocation API with Google Maps API</title> <meta charset="UTF-8" /> </head> <body> <script> function displayLocation(latitude,longitude){ var request = new XMLHttpRequest(); var method = 'GET'; var url = 'http://maps.googleapis.com/maps/api/geocode/json?latlng='+latitude+','+longitude+'&sensor=true'; var async = true; request.open(method, url, async); request.onreadystatechange = function(){ if(request.readyState == 4 && request.status == 200){ var data = JSON.parse(request.responseText); var address = data.results[0]; document.write(address.formatted_address); } }; request.send(); }; var successCallback = function(position){ var x = position.coords.latitude; var y = position.coords.longitude; displayLocation(x,y); }; var errorCallback = function(error){ var errorMessage = 'Unknown error'; switch(error.code) { case 1: errorMessage = 'Permission denied'; break; case 2: errorMessage = 'Position unavailable'; break; case 3: errorMessage = 'Timeout'; break; } document.write(errorMessage); }; var options = { enableHighAccuracy: true, timeout: 1000, maximumAge: 0 }; navigator.geolocation.getCurrentPosition(successCallback,errorCallback,options); </script> </body> </html>
这是一个使用承诺的现代解决scheme:
function getAddress (latitude, longitude) { return new Promise(function (resolve, reject) { var request = new XMLHttpRequest(); var method = 'GET'; var url = 'http://maps.googleapis.com/maps/api/geocode/json?latlng=' + latitude + ',' + longitude + '&sensor=true'; var async = true; request.open(method, url, async); request.onreadystatechange = function () { if (request.readyState == 4) { if (request.status == 200) { var data = JSON.parse(request.responseText); var address = data.results[0]; resolve(address); } else { reject(request.status); } } }; request.send(); }); };
并像这样调用它:
getAddress(lat, lon).then(console.log).catch(console.error);
promise将'then'中的地址对象返回或'catch'中的错误状态码
以下代码可以很好地获取城市名称(使用Google Map Geo API ):
HTML
<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>
脚本
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; } } ); }