Home > Article > Web Front-end > How to use Google Maps to display the current location in AngularJS_AngularJS
--In HTML5, we provide the navigator.geolocation.getCurrentPosition(f1, f2) function. f1 is the function called when positioning is successful, f2 is the function called when positioning fails, and the current geographical location information is used as Actual parameters are passed to the f1 and f2 functions. The f1 function just calls the Google Maps API.
How to display it?
--Need a prompt information and an area to display the map.
On thepage, it looks like this:
<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>
The Directive part is as follows:
(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); }());
The above is the relevant knowledge introduced by the editor to you on how to use Google Maps to display the current location in AngularJS. I hope it will be helpful to you.