可以在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>