使用javascript获取我的当前地址 [英] Get my current address using javascript

查看:116
本文介绍了使用javascript获取我的当前地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对使用Javascript获取当前地址很感兴趣,只是通过组装其他一些SO线程解决了这个问题( 2 a>),所以想发布此问题和答案.

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获取我的当前地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆