虽然城市切换可以由用户自行选择,偶尔客户需要定位用户的当前城市,作为默认城市选项。
大致搜罗了一下, 各地图(高德地图、百度地图、腾讯地图)都有相关api可实现该功能。只是相关信息的完整度和准确度有些差异,需要自行验证,比较全国城市也不少。
高德地图
获取位置信息的api有3种(暂时验证了2种),综合起来可获取的当前城市的行政区域编码、名称、中心点、边界坐标点信息。
0.jpg
1.jpg
代码demo:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="Access-Control-Allow-Origin" content="*">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>自动定位功能(浏览器)</title>
<style>
*{
margin: 0;
padding: 0;
}
body{
font-family:-apple-system-font,BlinkMacSystemFont,Helvetica Neue,PingFang SC,Hiragino Sans GB,Microsoft YaHei UI,Microsoft YaHei,Arial,sans-serif;
font-size: 14px;
line-height: 1.44;
color: #333;
}
.list-hd{
text-align: center;
color: #333;
font-size: 20px;
line-height: 2;
font-weight: bold;
}
.list{
position: relative;
}
.item{
margin: 10px;
padding: 10px;
border: 1px dashed #999;
}
.item .hd{
font-size: 1.2em;
font-weight: bold;
}
.item .ref{
color: #999;
}
.item .show{
color: #666;
}
.item .city{
font-size: 16px;
color: #333;
font-weight: bold;
font-style: italic;
}
</style>
</head>
<body>
<div id="container"></div>
<div class="list-hd">方案:高德地图</div>
<div class="list">
<div class="item">
<div class="hd">参考api:</div>
<div class="ref">
https://lbs.amap.com/api/jsapi-v2/guide/services/geolocation
</div>
</div>
<div class="item">
<div class="hd">法一:</div>
<div class="ref">
初始化地图时,无需传入对应参数就能获取大致的您的定位信息。
<br>
参考:https://lbs.amap.com/demo/jsapi-v2/example/location/map-is-initially-loaded-into-the-current-city
</div>
<div class="hd">位置信息:</div>
<div class="ref" id="city1">
</div>
</div>
<div class="item">
<div class="hd">法二:</div>
<div class="ref">
AMap.Geolocation(注:由于众多浏览器已不再支持非安全域的定位请求,为保位成功率和精度,请升级您的站点到HTTPS。)
<br>
参考:https://lbs.amap.com/demo/jsapi-v2/example/location/browser-location
</div>
<div class="hd">位置信息:</div>
<div class="ref" id="city2">
</div>
</div>
<div class="item">
<div class="hd">法三:<span style="color: #f00;">(推荐)</span></div>
<div class="ref">
AMap.CitySearch
</div>
<div class="hd">位置信息:</div>
<div class="ref" id="city3">
</div>
</div>
</div>
<!--高德地图-->
<script src="https://webapi.amap.com/maps?v=1.4.10&key=xxx&plugin=AMap.CitySearch,AMap.Geolocation"></script>
<script>
//初始化地图时,若center属性缺省,地图默认定位到用户所在城市的中心
var map = new AMap.Map('container', {
resizeEnable: true
});
//法一:
document.getElementById('city1').innerHTML='当前城市adcode:'+map.getAdcode()+'<br>'+
'当前中心点:'+map.getCenter();
//法二:
AMap.plugin('AMap.Geolocation', function() {
var geolocation = new AMap.Geolocation({
enableHighAccuracy: true,//是否使用高精度定位,默认:true
timeout: 10000, //超过10秒后停止定位,默认:5s
position:'RB', //定位按钮的停靠位置
offset: [10, 20], //定位按钮与设置的停靠位置的偏移量,默认:[10, 20]
zoomToAccuracy: true, //定位成功后是否自动调整地图视野到定位点
});
map.addControl(geolocation);
geolocation.getCurrentPosition(function(status,result){
if(status=='complete'){
onComplete(result)
}else{
onError(result)
}
});
});
//解析定位结果
function onComplete(data) {
var str = [];
str.push('定位结果:' + data.position);
str.push('定位类别:' + data.location_type);
if(data.accuracy){
str.push('精度:' + data.accuracy + ' 米');
}//如为IP精确定位结果则没有精度信息
str.push('是否经过偏移:' + (data.isConverted ? '是' : '否'));
document.getElementById('city2').innerHTML = '定位成功,'+str.join('<br>');
}
//解析定位错误信息
function onError(data) {
document.getElementById('city2').innerHTML = '定位失败,失败原因排查信息:'+data.message+'</br>浏览器返回信息:'+data.originMessage;
}
//法三:
//实例化城市查询类
var citysearch = new AMap.CitySearch();
//自动获取用户IP,返回当前城市
citysearch.getLocalCity(function(status, result) {
console.log('result:',result);
if (status === 'complete' && result.info === 'OK') {
if (result && result.city && result.bounds) {
var cityinfo = result.city;
document.getElementById('city3').innerHTML = '您当前所在城市:('+result.adcode+')'+cityinfo;
}
} else {
document.getElementById('city3').innerHTML = result.info;
}
});
</script>
</body>
</html>
百度地图
获取位置信息的api有2种,综合起来可获取的当前城市的行政区域编码、名称、中心点。
3.jpg 2.jpg
代码demo:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="Access-Control-Allow-Origin" content="*">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>自动定位功能(浏览器)-百度地图</title>
<style>
*{
margin: 0;
padding: 0;
}
body{
font-family:-apple-system-font,BlinkMacSystemFont,Helvetica Neue,PingFang SC,Hiragino Sans GB,Microsoft YaHei UI,Microsoft YaHei,Arial,sans-serif;
font-size: 14px;
line-height: 1.44;
color: #333;
}
.list-hd{
text-align: center;
color: #333;
font-size: 20px;
line-height: 2;
font-weight: bold;
}
.list{
position: relative;
}
.item{
margin: 10px;
padding: 10px;
border: 1px dashed #999;
}
.item .hd{
font-size: 1.2em;
font-weight: bold;
}
.item .ref{
color: #999;
}
.item .show{
color: #666;
}
.item .city{
font-size: 16px;
color: #333;
font-weight: bold;
font-style: italic;
}
</style>
</head>
<body>
<div class="list-hd">百度地图</div>
<div class="list">
<div class="item">
<div class="hd">法一:</div>
<div class="ref">
<div>参考:</div>
<div>
<a href="http://api.map.baidu.com/location/ip?ak=xxx">http://api.map.baidu.com/location/ip?ak=xxx</a>
</div>
</div>
<div class="show">
<div>定位城市信息:</div>
<div class="city" id="city_bd"></div>
</div>
</div>
<div class="item">
<div class="hd">法二:</div>
<div class="ref">
<div>参考:</div>
<div>
<a href="">BMap.LocalCity</a>
</div>
</div>
<div class="show">
<div>定位城市信息:</div>
<div class="city" id="city_bd2"></div>
</div>
</div>
</div>
<!--jquery-->
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
<!--百度地图-->
<script src="http://api.map.baidu.com/api?v=2.0&ak=xxx"></script>
<script>
$(function () {
//百度地图定位方案一
function getCityByBaidu(){
$.ajax({
url: 'http://api.map.baidu.com/location/ip?ak=xxx',
type: 'POST',
dataType: 'jsonp',
success:function(data) {
console.log('百度定位:', data);
let cityInfo = '';
cityInfo += data.content.address+'<br>';
$('#city_bd').html(cityInfo);
}
})
}
//百度地图定位方案二
function getCityByBaidu2(){
//百度地图获取城市名称的方法
let getCurrentCityName = function () {
return new Promise(function (resolve, reject) {
let myCity = new BMap.LocalCity()
myCity.get(function (result) {
resolve(result)
})
})
}
getCurrentCityName().then(data=>{
console.log('百度定位2:', data);
$('#city_bd2').html(data.name);
});
}
//调试
getCityByBaidu();//百度定位
getCityByBaidu2();//百度定位2
});
</script>
</body>
</html>
腾讯地图
按照文档api可获取的信息不少。
{ "module":"geolocation", "nation": "中国", "province": "广东省", "city":"深圳市", "district":"南山区", "adcode":"440305", //行政区ID,六位数字, 前两位是省,中间是市,后面两位是区,比如深圳市ID为440300 "addr":"深圳大学杜鹃山(白石路北250米)", "lat":22.530001, //火星坐标(gcj02),腾讯、Google、高德通用 "lng":113.935364, "accuracy":13 //误差范围,以米为单位 }
代码demo:
见https://lbs.qq.com/webApi/component/componentGuide/componentGeolocation
网友评论