我可以从以下代码中检索经度/经度。根据这个值,我应该能够获得城市名称。
<!DOCTYPE html>
<html>
<body>
<p>Click the button to get your coordinates.</p>
<button onclick="getLocation()">Try It</button>
<p id="demo"></p>
<script>
var x = document.getElementById("demo");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
x.innerHTML = "Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
var geocoder;
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(position.coords.latitude, position.coords.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];
alert("city name is: " + city);
}
else {
alert("address not found");
}
}
else {
alert("Geocoder failed due to: " + status);
}
}
</script>
</body>
</html>我从一些文章中读到了Geo-location API。我不确定这是不是真的需要,因为我没有在这里实现地图。我只需要现在所在城市的名字
发布于 2018-09-04 16:49:33
这取决于你的目的。如果您想在小范围内使用此应用程序,最好在数据库中硬编码城市名称和经度/纬度,然后可以获取当前的经度/纬度,并检查数据库中的匹配项以获得一定的准确率。这取决于你的需要。
https://stackoverflow.com/questions/52162131
复制相似问题