微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

javascript – 如何从手机间隙的纬度和经度获取城市名称?

我可以从当前纬度和经度得到完整的地址.但是如何才能从完整地址获取城市名称.这是我的代码.
var geocoder;
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(latitude,longitude);
//alert("Else loop" + latlng);
geocoder.geocode({
    'latLng': latlng
},function(results,status) {
    //alert("Else loop1");
    if (status == google.maps.GeocoderStatus.OK) {
        if (results[0]) {
            var add = results[0].formatted_address;
            alert("Full address is: " + add);
        } else {
            alert("address not found");
        }
    } else {
        //document.getElementById("location").innerHTML="Geocoder Failed due to: " + status;
        //alert("Geocoder Failed due to: " + status);
    }
});

解决方法

var geocoder;
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(latitude,longitude);

geocoder.geocode(
    {'latLng': latlng},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);
        }
    }
);

用“,”作为分隔符分割完整地址获取城市名称.

原文地址:https://www.jb51.cc/js/153658.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐