我可以从以下代码中获取经度/纬度。并基于此值,我应该能够获得城市名称。
<!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>
我从一些文章中了解了地理位置API。而且我不确定这是否确实需要,因为我没有在这里实现地图。我只需要当前位置的城市名称
答案 0 :(得分:0)
这取决于您的目的。如果要在较小的区域内使用此应用程序,最好在数据库中对城市名称和纬度/经度进行硬编码,此后,您可以获取当前纬度/经度并检查数据库中的匹配项,以确保准确性。这取决于您的需求。