AngularJS +谷歌地图没有显示标记

时间:2016-09-26 21:45:21

标签: javascript angularjs google-maps ionic-framework

我有一个标记在$ scope.mapCreated上工作正常。现在,我试图在用户点击$ scope.centerOnMe()时显示另一个标记,但只显示当前位置而没有标记。

我是否必须使用this example或者是否有最简单的解决方案?

控制器

.controller('mapCtrl', ['$scope', '$state', '$ionicLoading', function($scope, $state, $ionicLoading){

$scope.mapCreated = function(map) {

    var latlngPlace = new google.maps.LatLng(-27.4264356, -51.7838787);
    var marker = new google.maps.Marker({
        map: map,
        position: latlngPlace
    });

    $scope.map = map;
};

$scope.centerOnMe = function () {
console.log("Centering");
if (!$scope.map) {
  return;
}

$scope.loading = $ionicLoading.show({
  content: 'Wait...',
  showBackdrop: false
});

navigator.geolocation.getCurrentPosition(function (pos) {
  console.log('Got pos', pos);

  $scope.map.setCenter(new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude));

    var myPlace = new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude);

    var marker2 = new google.maps.Marker({
        position: myPlace
    });


  $ionicLoading.hide();

}, function (error) {

    console.log('Error' + error.message)
});
};    

}])

directives.js

angular.module('app.directives', [])

.directive('map', function(){

return {
restrict: 'E',
scope: {
  onCreate: '&'
},
link: function ($scope, $element, $attr) {
  function initialize() {
    var mapOptions = {
      center: new google.maps.LatLng(-27.426102, -51.784999),
      zoom: 16,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    var map = new google.maps.Map($element[0], mapOptions);

    $scope.onCreate({map: map});

    // Stop the side bar from dragging when mousedown/tapdown on the map
    google.maps.event.addDomListener($element[0], 'mousedown', function (e)  {
      e.preventDefault();
      return false;
    });
  }

  if (document.readyState === "complete") {
    initialize();
  } else {
    google.maps.event.addDomListener(window, 'load', initialize);
  }
}
}

});

map.html

<ion-view title="Map" id="page9" style="background-color:#FFFFFF;">
<ion-content>
    <map on-create="mapCreated(map)"></map>
</ion-content>
<ion-footer-bar class="bar-stable bar-calm">
  <a ng-click="centerOnMe()" class="button button-icon icon ion-navigate">FindMe</a>
</ion-footer-bar>
</ion-view>

2 个答案:

答案 0 :(得分:1)

您可以在centerOnMe()功能中创建新标记。以下是创建新标记的示例。这是创建标记的唯一方法。

$scope.centerOnMe = function () {
  console.log("Centering");
  // Adding a new marker
  var marker1 = new google.maps.Marker({
    map: $scope.map,
    position:  new google.maps.LatLng(lat, lng);
  });

  if (!$scope.map) {
     return;
  }
}

答案 1 :(得分:0)

它只是错过了地图:$ scope.map

var myPlace = new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude);

var marker2 = new google.maps.Marker({
    map: $scope.map,
    position: myPlace
});