1. 程式人生 > >js 獲取定位地址

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>