幾乎每個APP都會有地圖 所以在這裏記錄一下
1.在index.html 中
1 2 3 4 5
2. CSS
1 map {2 display: block;3 width: 100%;4 height: 100%;5 }6 .scroll {7 height: 100%;8 }
3. 生成一個指令
1 .directive('map', function() { 2 return { 3 restrict: 'E', 4 scope: { 5 onCreate: '&' 6 }, 7 link: function ($scope, $element, $attr) { 8 function initialize() { 9 var mylang=new google.maps.LatLng(43.07493, -89.381388);10 var mapOptions = {11 center: mylang,12 zoom: 16,13 mapTypeId: google.maps.MapTypeId.ROADMAP14 };15 var map = new google.maps.Map($element[0], mapOptions);16 //Marker + infowindow + angularjs compiled ng-click17 var marker = new google.maps.Marker({18 position: mylang,19 map: map,20 title: 'Uluru (Ayers Rock)'21 });22 var infowindow = new google.maps.InfoWindow({23 content:"Hello World!"24 });25 google.maps.event.addListener(marker, 'click', function() {26 infowindow.open(map,marker);27 });28 $scope.onCreate({map: map});29 30 //Stop the side bar from dragging when mousedown / tapdown on the map31 google.maps.event.addDomListener($element[0], 'mousedown', function (e) {32 e.preventDefault();33 return false;34 });35 }36 37 if (document.readyState === "complete") {38 initialize();39 } else {40 google.maps.event.addDomListener(window, 'load', initialize);41 }42 }43 }44 });
4.在index.html 中寫入 map 標籤 1 <map on-create="mapCreated(map)"></map>
5.設置控制器
1 .controller('MapCtrl', function($scope, $ionicLoading, $cordovaGeolocation) { 2 $scope.mapCreated = function(map) { 3 $scope.map = map; 4 }; 5 6 $scope.centerOnMe = function() { 7 console.log("Centering"); 8 if (!$scope.map) { 9 return;10 }11 12 $scope.loading = $ionicLoading.show({13 content: 'Getting current location...',14 showBackdrop: false15 });16 $cordovaGeolocation17 .getCurrentPosition()18 .then(function(pos) {19 var lat = pos.coords.latitude20 var long = pos.coords.longitude21 console.log('Got pos', pos);22 $scope.map.setCenter(new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude));//23 var marker=new google.maps.Marker({24 map: $scope.map,25 position: new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude)26 });//這個marker 設置了一下 27 $scope.loading.hide();28 }, function(err) {29 // error30 });31 // navigator.geolocation.getCurrentPosition(function (pos) { 32 // console.log('Got pos', pos);33 // $scope.map.setCenter(new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude));34 // var marker=new google.maps.Marker({ 35 // map: $scope.map,36 // position: new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude)37 // });38 // $scope.loading.hide();39 // }, function (error) { 40 // alert('Unable to get location: ' + error.message);41 // });42 };43 });
6. 忘記了...為了更加的準確 還是添加了ngcordova plugin 插件
1 cordova plugin add org.apache.cordova.geolocation 不要忘記了注入 ngCordova $cordovaGeolocation