在AngularJS中如何使用谷歌地图把当前位置显示出来
--在html5中,为我们提供了navigator.geolocation.getCurrentPosition(f1,f2)函数,f1是定位成功调用的函数,f2是定位失败调用的函数,而且会把当前的地理位置信息作为实参传递给f1和f2函数。f1函数调用谷歌地图的API即可。
如何展示呢?
--需要一个提示信息和展示地图的一个区域。
页面上,大致是这样:
<map-geo-locationheight="400"width="600"></map-geo-location> <scriptsrc="angular.js"></script> <scriptsrc="http://maps.google.com/maps/api/js?sensor=false"></script> <scriptsrc=="mapGeoLocation.js"></script>
Directive部分如下:
(function(){
varmapGeoLocation=['$window',function($window){
vartemplate='<p><spanid="status">正在查找地址...</span></p>'+'<br/><divid="map"></div>',
mapContainer=null,
status=null;
functionlink(scope,elem,attrs){
//以Angular的方式获取Angular元素
status=angular.element(document.getElementById('status'));
mapContainer=angular.element(document.getElementById('map'));
mapContainer.attr('style','height:'+scope.height+'px;width:'+scope.width+'px');
$window.navigator.geolocation.getCurrentPosition(mapLocation,geoError);
}
//定位成功时调用
functionmapLocation(pos){
status.html('foundyourlocation!Longitude:'+pos.coords.longitude+'Latitude:'+pos.coords.latitude);
varlatlng=newgoogle.maps.LatLng(pos.coords.latitude,pos.coords.longitude);
varoptons={
zoom:15,
center:latlng,
myTypeCOntrol:true,
mapTypeId:google.maps.MapTypeId.ROADMAP
};
varmap=newgoogle.maps.Map(mapContainer[0],options);
varmarker=newgoogle.maps.Markser({
position:latlng,
map:map,
title:"Yourlocation"
});
}
//定位失败时调用
functiongeoError(error){
status.html('failedlookup'+error.message);
}
return{
restrict:'EA',//默认
scope:{
height:'@',
width:'@'
},
link:link,
template:template
}
}];
angular.module('direcitveModule',[])
.direcitve('mapGeoLocation',mapGeoLocation);
}());
以上所述是小编给大家介绍的在AngularJS中如何使用谷歌地图把当前位置显示出来的相关知识,希望对大家有所帮助。