如何显示街道,城市和国家的移动设备的当前位置

时间:2013-02-02 11:08:58

标签: javascript jquery cordova geolocation

以下是我为了获取移动设备的当前位置而编写的代码。它显示了移动设备的城市和国家/地区的当前位置。但是我需要显示街道地址位置。     请尽快咨询。

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width;height=device-height; user-scalable=no" />
<meta http-equiv="Content-type" content="text/html;charset=utf-8">
<title>PhoneGap Reverse Geolocation Lookup</title>
<script type="text/javascript" src="cordova-1.7.0.js"></script>
<script type="text/javascript" src="jquery-1.7.2.min.js"></script>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=true"></script>
<script type="text/javascript">
var geocoder;
$(document).ready(function() {
geocoder = new google.maps.Geocoder();
$('#button-get-reverse-lookup').click(function(){
navigator.geolocation.getCurrentPosition(onGetCurrentPositionSuccess, onGetCurrentPositionError);
});
});
var onGetCurrentPositionSuccess = function(position) {
console.log("lat: " + position.coords.latitude);
console.log("long: " + position.coords.longitude);
var lat = parseFloat(position.coords.latitude);
var lng = parseFloat(position.coords.longitude);
// paris, france - uncomment to test
//var lat = parseFloat(48.850258);
//var lng = parseFloat(2.351074);
// tiburon, california
//var lat = parseFloat(37.872685);
//var lng = parseFloat(-122.45224);
var latlng = new google.maps.LatLng(lat, lng);
geocoder.geocode({'latLng': latlng}, function(results, status)
{
 if (status == google.maps.GeocoderStatus.OK)
                {
                    if (results[1])
                    {
                        var reverse_geo = results[1];

                         if (reverse_geo.address_components[0])
                          { 

                          alert(reverse_geo.address_components[4].long_name+"," + reverse_geo.address_components[3].long_name+"," + reverse_geo.address_components[2].long_name+"," + reverse_geo.address_components[0].long_name);
                          //text = text + "0: " + reverse_geo.address_components[0].long_name + "<br />"1: " + reverse_geo.address_components[1].long_name + "<br />""; 
                          }
                       }
                }
                else
                {
                    alert("No hay informaci�n de Reverse Geocoding.");
                }
});
}
var onGetCurrentPositionError = function(error) {
console.log("Couldn't get geo coords from device");
}
</script>
</head>

<body>
<h1>Reverse Geolocation Lookup</h1>
<button id="button-get-reverse-lookup">Get Reverse Lookup</button>
</body>
</html> 

1 个答案:

答案 0 :(得分:0)

根据docs on Google site,您需要循环查看所有类型的地址组件,并将它们与您想要提取的内容进行比较。

street_number =街道号码 route =街道名称 locality =城市 administrative_area_level_1 =州或省 country =国家

无法保证地址组件的递送顺序,因此您需要检查它们。