利用百度地圖API獲取當前位置信息


利用百度地圖API可以做很多事情,個人感覺最核心也是最基礎的就是定位功能了。這里分享一個制作的JS可以實現登錄網頁后定位:

 1 <script type="text/javascript"> 
 2 var map; 
 3 var gpsPoint; 
 4 var baiduPoint; 
 5 var gpsAddress; 
 6 var baiduAddress; 
 7 var x;
 8 var y;
 9 function getLocation() { 
10 //根據IP獲取城市 
11 var myCity = new BMap.LocalCity(); 
12 myCity.get(getCityByIP); 
13 
14 //獲取GPS坐標 
15 if (navigator.geolocation) { 
16 navigator.geolocation.getCurrentPosition(showMap, handleError, { enableHighAccuracy: true, maximumAge: 1000 }); 
17 } else { 
18 alert("您的瀏覽器不支持使用HTML 5來獲取地理位置服務"); 
19 } 
20 } 
21 
22 function showMap(value) { 
23 var longitude = value.coords.longitude; 
24 var latitude = value.coords.latitude; 
25 map = new BMap.Map("map"); 
26 x=latitude;
27 y=longitude;
28 //alert("坐標經度為:" + latitude + ", 緯度為:" + longitude ); 
29 gpsPoint = new BMap.Point(longitude, latitude); // 創建點坐標 
30 
31 
32 //根據坐標逆解析地址 
33 var geoc = new BMap.Geocoder(); 
34 geoc.getLocation(gpsPoint, getCityByCoordinate); 
35 
36 BMap.Convertor.translate(gpsPoint, 0, translateCallback); 
37 map.enableScrollWheelZoom(true);
38 } 
39 
40 translateCallback = function (point) { 
41 baiduPoint = point; 
42 map.centerAndZoom(baiduPoint, 18); 
43 var geoc = new BMap.Geocoder(); 
44 geoc.getLocation(baiduPoint, getCityByBaiduCoordinate); 
45 } 
46 
47 function getCityByCoordinate(rs) { 
48 gpsAddress = rs.addressComponents; 
49 var address = "GPS標注:" + gpsAddress.province + "," + gpsAddress.city + "," + gpsAddress.district + "," + gpsAddress.street + "," + gpsAddress.streetNumber; 
50 var marker = new BMap.Marker(gpsPoint); // 創建標注 
51 map.addOverlay(marker); // 將標注添加到地圖中 
52 var labelgps = new BMap.Label(address, { offset: new BMap.Size(20, -10) }); 
53 marker.setLabel(labelgps); //添加GPS標注 
54 } 
55 
56 function getCityByBaiduCoordinate(rs) { 
57 baiduAddress = rs.addressComponents; 
58 var address = "百度標注:" + baiduAddress.province + "," + baiduAddress.city + "," + baiduAddress.district + "," + baiduAddress.street + "," + baiduAddress.streetNumber; 
59 var marker = new BMap.Marker(baiduPoint); // 創建標注 
60 map.addOverlay(marker); // 將標注添加到地圖中 
61 var labelbaidu = new BMap.Label(address, { offset: new BMap.Size(20, -10) }); 
62 marker.setLabel(labelbaidu); //添加百度標注 
63 } 
64 
65 //根據IP獲取城市 
66 function getCityByIP(rs) { 
67 var cityName = rs.name; 
68 alert("根據IP定位您所在的城市為:" + cityName); 
69 } 
70 
71 function handleError(value) { 
72 switch (value.code) { 
73 case 1: 
74 alert("位置服務被拒絕"); 
75 break; 
76 case 2: 
77 alert("暫時獲取不到位置信息"); 
78 break; 
79 case 3: 
80 alert("獲取信息超時"); 
81 break; 
82 case 4: 
83 alert("未知錯誤"); 
84 break; 
85 } 
86 } 
87 
88 function init() { 
89 getLocation(); 
90 } 
91 
92 window.onload = init; 
93 
94 </script>

完成定位功能后可以添加相關代碼編輯地圖控件 覆蓋物 信息窗口等等各種功能。

附上百度地圖連接:http://lbsyun.baidu.com/

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM