我对使用 Javascript 获取当前地址很感兴趣,只是通过组装其他一些 SO 线程来解决这个问题(1,2) 所以想发布这个问题和答案.
I was interested in getting my current address using Javascript and just figured this out by assembling some other SO threads (1,2) so wanted to post this question and answer.
请看下面的答案.
这是 HTML:
<script src="http://maps.google.com/maps/api/js?sensor=false"></script>
<p id='latitudeAndLongitude'></p>
<p id='address'></p>
这是 JS:
var latitudeAndLongitude=document.getElementById("latitudeAndLongitude"),
location={
latitude:'',
longitude:''
};
if (navigator.geolocation){
navigator.geolocation.getCurrentPosition(showPosition);
}
else{
latitudeAndLongitude.innerHTML="Geolocation is not supported by this browser.";
}
function showPosition(position){
location.latitude=position.coords.latitude;
location.longitude=position.coords.longitude;
latitudeAndLongitude.innerHTML="Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
var geocoder = new google.maps.Geocoder();
var latLng = new google.maps.LatLng(location.latitude, location.longitude);
if (geocoder) {
geocoder.geocode({ 'latLng': latLng}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
console.log(results[0].formatted_address);
$('#address').html('Address:'+results[0].formatted_address);
}
else {
$('#address').html('Geocoding failed: '+status);
console.log("Geocoding failed: " + status);
}
}); //geocoder.geocode()
}
} //showPosition
这篇关于使用 javascript 获取我当前的地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!