如何使用谷歌地圖把當前位置顯示出來呢?
--在html5中,為我們提供了navigator.geolocation.getCurrentPosition(f1, f2)函式,f1是定位成功呼叫的函式,f2是定位失敗呼叫的函式,而且會把當前的地理位置資訊作為實參傳遞給f1和f2函式。f1函式呼叫谷歌地圖的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); }());