地圖與地理定位
定位在大部分項目中都需要實現,如何實現主要有如下的幾種方法
-
H5定位
在HTML5中navigator有很強大的功能,其中就有定位的方法
navigator.geolocation.getCurrentPosition(function showPosition(position){ lat=position.coords.latitude; lon=position.coords.longitude; console.log(lat,lon) },function(err){ console.log(err) });
這個服務其實是谷歌提供的,在我們國內使用的可能性較低
-
后端定位
前端調用一個后端提供的接口,后端進行定位操作,返回給前端
在工作中公司后端是可以給你調接口的!!(也不一定要自己弄,可以直接讓后端搞。。嘿嘿) -
利用百度地圖API/高德地圖API...定位
獲取坐標,取回地點
<script src="http://webapi.amap.com/maps?v=1.4.2&key=025f0c88ec8249226cfc528b6e83c535(key值可以從高德地圖api獲取key值這
是筆者自己申請的key值)&plugin=AMap.Geocoder"></script>
<script>
var map, geolocation;
//加載地圖,調用瀏覽器定位服務
map = new AMap.Map('container', {
resizeEnable: true
});
map.plugin('AMap.Geolocation', function() {
geolocation = new AMap.Geolocation({
enableHighAccuracy: true,//是否使用高精度定位,默認:true
timeout: 20000, //超過10秒后停止定位,默認:無窮大
buttonOffset: new AMap.Pixel(10, 20),//定位按鈕與設置的停靠位置的偏移量,默認:Pixel(10, 20)
zoomToAccuracy: true, //定位成功后調整地圖視野范圍使定位位置及精度范圍視野內可見,默認:false
buttonPosition:'RB'
});
geolocation.getCurrentPosition();
AMap.event.addListener(geolocation, 'complete', function onComplete(data) {
console.log(data.position.getLat(),data.position.getLng())
regeocoder([data.position.getLng(),data.position.getLat()])
});//返回定位信息
});
function regeocoder(pos) { //逆地理編碼
var geocoder = new AMap.Geocoder({
radius: 1000,
extensions: "all"
});
geocoder.getAddress(pos, function(status, result) {
if (status === 'complete' && result.info === 'OK') {
console.log(result)
}
});
}
</script>
在國內地圖應用公司主要有這么幾個:百度-百度地圖,騰訊-騰訊地圖,阿里-高德地圖,搜狗-搜狗地圖..
這些地圖都會為開發者提供一些便利來使用其中的一些功能
做一個自己的地圖
<style>
#map{
width: 100%;
height: 100vh;
}
</style>
<div id="map"></div>
<script src="http://webapi.amap.com/maps?v=1.4.2&key=4e2c29a761a9c245ddd69c5e64be66a5"></script>
<script>
var map = new AMap.Map('map', {
resizeEnable: true,
zoom:11,
center: [116.397428, 39.90923]
});
</script>