1. 程式人生 > >利用百度地圖API獲取當前位置信息

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

avi text 核心 baidu lee local break position erl

利用百度地圖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/

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