--在html5中,為我們提供了navigator.geolocation.getCurrentPosition(f1, f2)函數,f1是定位成功調用的函數,f2是定位失敗調用的函數,而且會把當前的地理位置資訊作為實參傳遞給f1和f2函數。f1函數調用Google地圖的API即可。
如何展示呢?
--需要一個提示資訊和展示地圖的一個地區。
頁面上,大致是這樣:
<map-geo-location height="400" width="600"></map-geo-location><script src="angular.js"></script><script src="http://maps.google.com/maps/api/js?sensor=false"></script><script src=="mapGeoLocation.js"></script>
Directive部分如下:
(function(){var mapGeoLocation = ['$window', function($window){var template = '<p><span id="status">正在尋找地址...</span></p>' + '<br /><div id="map"></div>',mapContainer = null,status = null;function link(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);}//定位成功時調用function mapLocation(pos){status.html('found your location! Longitude: ' + pos.coords.longitude + ' Latitude: ' + pos.coords.latitude);var latlng = new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude);var optons = {zoom:15,center: latlng,myTypeCOntrol: true,mapTypeId: google.maps.MapTypeId.ROADMAP};var map = new google.maps.Map(mapContainer[0], options);var marker = new google.maps.Markser({position: latlng,map: map, title: "Your location"});}//定位失敗時調用function geoError(error){status.html('failed lookup ' + error.message);}return {restrict: 'EA', //預設scope:{height: '@',width:'@'},link: link,template: template}}];angular.module('direcitveModule',[]).direcitve('mapGeoLocation', mapGeoLocation);}());
以上所述是小編給大家介紹的在AngularJS中如何使用Google地圖把當前位置顯示出來的相關知識,希望對大家有所協助。