js 获取定位地址

最近一段要做天气预报,使用了高德的接口,好用又免费,可是接口需要当前的地址信息,刚开始是想用IP定位,天真的以为每个城市的IP应该都是不一样的,结果回家一测,

发现自己家的方正宽带IP是北京的,顿时一万点暴击,只好另寻它法。找到了百度和腾讯的API接口试用了一下,定位结果很是失望,但是还是记录一下吧。

腾讯地图

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>定位</title>
 6     <meta name="viewport" content="width=device-width,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no">
 7     <script src="./jquery-1.11.0.js"></script>
 8 </head>
 9 <body style="margin:0px;padding: 0px">
10 
11 </body>
12 <script>
13 $.getScript('https://apis.map.qq.com/ws/location/v1/ip?callback=showLocation&key=自己的&output=jsonp');
14 function showLocation(data) {
15    console.log(data.result.ad_info.city);
16    alert(data.result.ad_info.district);
17 }
18 </script>
19 </html>

百度地图

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>定位</title>
 6     <meta name="viewport" content="width=device-width,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no">
 7     <script src="./jquery-1.11.0.js"></script>
 8     <!-- <script type="text/javascript" src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script> -->
 9     <!-- <script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=dGIGH33oqvOqRGkNUS4Bw0veSB6ELiZl2IoX7vBXcaCijycBIl1"></script> -->
10 </head>
11 <body style="margin:0px;padding: 0px">
12 
13 </body>
14 <script>
15  
16  $.getScript("https://api.map.baidu.com/location/ip?ak=自己的&callback=showLocation");
17    function showLocation(data) {
18     console.log(data.content.address_detail.city);
19     alert(data.content.address_detail.city);
20     alert(data.content.address_detail.province);
21      } 
22 </script>
23 </html>

思前想后,由于是做公众号开发,还是决定用腾讯自家的地图吧(以前用的都是高德)

再看腾讯 API 的时候 发现一个组件,精确定位

 1 <!DOCTYPE html>
 2 <html>
 3 <head>
 4     <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 5     <title>前端定位模块</title>
 6     <meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no">
 7     <style>
 8         * {
 9             margin: 0;
10             padding: 0;
11             border: 0;
12         }
13         body {
14             position: absolute;
15             width: 100%;
16             height: 100%;
17             text-align: center;
18         }
19         #pos-area {
20             background-color: #009DDC;
21             margin-bottom: 10px;
22             width: 100%;
23             overflow: scroll;
24             text-align: left;
25             color: white;
26         }
27         #demo {
28             padding: 8px;
29             font-size: small;
30         }
31         #btn-area {
32             height: 100px;
33         }
34         button {
35             margin-bottom: 10px;
36             padding: 12px 8px;
37             width: 42%;
38             border-radius: 8px;
39             background-color: #009DDC;
40             color: white;
41         }
42     </style>
43     <script type="text/javascript" src="https://3gimg.qq.com/lightmap/components/geolocation/geolocation.min.js"></script>
44 </head>
45 <body>
46     <div id="pos-area">
47         <p id="demo">点击下面的按钮,获得对应信息:<br /></p>
48     </div>
49  
50     <div id="btn-area">
51         <button onClick="geolocation.getLocation(showPosition, showErr, options)">获取精确定位信息</button>
52         <button onClick="geolocation.getIpLocation(showPosition, showErr)">获取粗糙定位信息</button>
53         <button onClick="showWatchPosition()">开始监听位置</button>
54         <button onClick="showClearWatch()">停止监听位置</button>
55     </div>
56     <script type="text/JavaScript">
57         var geolocation = new qq.maps.Geolocation("自己的key", "域名");
58  
59         document.getElementById("pos-area").style.height = (document.body.clientHeight - 110) + 'px';
60  
61         var positionNum = 0;
62         var options = {timeout: 8000};
63         function showPosition(position) {
64             positionNum ++;
65             document.getElementById("demo").innerHTML += "序号:" + positionNum;
66             document.getElementById("demo").appendChild(document.createElement('pre')).innerHTML = JSON.stringify(position, null, 4);
67             document.getElementById("pos-area").scrollTop = document.getElementById("pos-area").scrollHeight;
68         };
69  
70         function showErr() {
71             positionNum ++;
72             document.getElementById("demo").innerHTML += "序号:" + positionNum;
73             document.getElementById("demo").appendChild(document.createElement('p')).innerHTML = "定位失败!";
74             document.getElementById("pos-area").scrollTop = document.getElementById("pos-area").scrollHeight;
75         };
76  
77         function showWatchPosition() {
78             document.getElementById("demo").innerHTML += "开始监听位置!<br /><br />";
79             geolocation.watchPosition(showPosition);
80             document.getElementById("pos-area").scrollTop = document.getElementById("pos-area").scrollHeight;
81         };
82  
83         function showClearWatch() {
84             geolocation.clearWatch();
85             document.getElementById("demo").innerHTML += "停止监听位置!<br /><br />";
86             document.getElementById("pos-area").scrollTop = document.getElementById("pos-area").scrollHeight;
87         };
88     </script>
89 </body>
90 </html>

初步测试下还是挺准的,无论是WIFI  还是  4G  都是挺好用的,还有待时间检验。

第一次用的是微信公众号开发自带的定位,就是需要后台签名的那种,但是反应速度太慢,所以才想一个更快的方法,顺便把天气代码也记录一下

<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no, width=device-width">
    <title>天气预报查询</title>
    <link rel="stylesheet" href="https://a.amap.com/jsapi_demos/static/demo-center/css/demo-center.css" />
    <style type="text/css">
        html,body,#container{
            height:100%;
        }
        .weather{
            width:5rem;
            display:inline-block;
            padding-left:0.5rem;
        }
        .sharp{
            height: 1rem;
            width: 1rem;
            background-color: white;
            transform: rotateZ(45deg);
            box-shadow: 2px 2px 3px rgba(114, 124, 245, .5);
            position: inherit;
            margin-left: 10.5rem;
            margin-top: -6px;
        }
    </style>
</head>
<body>
<div id="container"></div>
<div class="info">
    <h4>预报天气</h4><hr>
    <p id='forecast'></p>
</div>
<script type="text/javascript" src="https://webapi.amap.com/maps?v=1.4.10&key=您申请的key值"></script>
<script type="text/javascript">
    var map = new AMap.Map('container', {
        resizeEnable: true,
        center: [116.486409,39.921489],
        zoom: 12
    });
    AMap.plugin('AMap.Weather', function() {
        var weather = new AMap.Weather();
        //查询实时天气信息, 查询的城市到行政级别的城市,如朝阳区、杭州市
        weather.getLive('朝阳区', function(err, data) {
            if (!err) {
                var str = [];
                str.push('<h4 >实时天气' + '</h4><hr>');
                str.push('<p>城市/区:' + data.city + '</p>');
                str.push('<p>天气:' + data.weather + '</p>');
                str.push('<p>温度:' + data.temperature + '℃</p>');
                str.push('<p>风向:' + data.windDirection + '</p>');
                str.push('<p>风力:' + data.windPower + ' 级</p>');
                str.push('<p>空气湿度:' + data.humidity + '</p>');
                str.push('<p>发布时间:' + data.reportTime + '</p>');
                var marker = new AMap.Marker({map: map, position: map.getCenter()});
                var infoWin = new AMap.InfoWindow({
                    content: '<div class="info" style="position:inherit;margin-bottom:0;">'+str.join('')+'</div><div class="sharp"></div>',
                    isCustom:true,
                    offset: new AMap.Pixel(0, -37)
                });
                infoWin.open(map, marker.getPosition());
                marker.on('mouseover', function() {
                    infoWin.open(map, marker.getPosition());
                });
            }
        });
        //未来4天天气预报
        weather.getForecast('朝阳区', function(err, data) {
            if (err) {return;}
            var str = [];
            for (var i = 0,dayWeather; i < data.forecasts.length; i++) {
                dayWeather = data.forecasts[i];
                str.push(dayWeather.date+' <span class="weather">'+dayWeather.dayWeather+'</span> '+ dayWeather.nightTemp + '~' + dayWeather.dayTemp + '');
            }
            document.getElementById('forecast').innerHTML = str.join('<br>');
        });
    });
</script>
</body>
</html>

猜你喜欢

转载自www.cnblogs.com/cwmizlp/p/9972972.html
今日推荐