自动定位城市

虽然城市切换可以由用户自行选择,偶尔客户需要定位用户的当前城市,作为默认城市选项。

大致搜罗了一下, 各地图(高德地图、百度地图、腾讯地图)都有相关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

参考

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 160,026评论 4 364
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,655评论 1 296
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,726评论 0 244
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,204评论 0 213
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,558评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,731评论 1 222
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,944评论 2 314
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,698评论 0 203
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,438评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,633评论 2 247
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,125评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,444评论 3 255
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,137评论 3 238
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,103评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,888评论 0 197
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,772评论 2 276
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,669评论 2 271

推荐阅读更多精彩内容