js调用高德API获取所在当前城市

可以在js代码中直接调用API接口,获取所处当前城市信息,代码如下:

<script type="text/javascript">
    
    function getCurrentCity(){
        $.ajax({
            type: "get",
            url: "http://webapi.amap.com/maps/ipLocation?key=608d75903d29ad471362f8c58c550daf",
            dataType: 'text',
            success: function(data) {
                //转换为JSON对象
                var jsonObj = eval("(" + data.replace('(','').replace(')','').replace(';','') + ")");
                //当前城市
                $("#cityName").html(jsonObj.city);
            }
        });
    }
    
    //页面加载获取当前所在城市信息
    $(document).ready(function(){
        getCurrentCity();
    });
</script>

猜你喜欢

转载自blog.csdn.net/chendongpu/article/details/112990502