在Ionic中使用多个标记的Google地图自动缩放

时间:2015-12-03 09:02:20

标签: javascript angularjs google-maps ionic-framework

directive.js:

.directive('map', function() {
  return {
    restrict: 'E',
    scope: {
      onCreate: '&'
    },
    link: function ($scope, $element, $attr) {
      function initialize() {
        var mapOptions = {
          center: new google.maps.LatLng(43.07493, -89.381388),
          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);
      }
    }
  }
});

HTML:

<map on-create="mapCreated(map)" data-tap-disabled="true"></map>

controller.js:

//Map controller
$scope.mapCreated = function (map) {
    $scope.map = map;
    $scope.map.setCenter(new google.maps.LatLng(latitude1, longitude1));
    createMarker(latitude1, longitude1, icon1);
    createMarker(latitude2, longitude2, icon2);             

    //Create marker
    var createMarker = function (lat, long, icon) {
        var marker = new google.maps.Marker({
            position: new google.maps.LatLng(lat, long),
            map: map,
            icon: icon,
        });
    }
};

假设“latitude1,longitude1,latitude2,longitude2,icon1和icon2”已初始化。

我的代码没有出错,但它没有缩小地图以显示所有标记。我以前做了一些研究,但我找不到合适的答案。谢谢你的帮助。

1 个答案:

答案 0 :(得分:1)

您需要停用data-tap http://ionicframework.com/docs/api/page/tap/允许googlemaps处理点击事件。

<ion-view>
...
<ion-content scroll="false">
    <map on-create="mapCreated(map)" data-tap-disabled="true"></map>
</ion-content>
...
</ion-view>