简体   繁体   中英

Angular leaflet directive zoom to marker on the center of the map

Dear fellow programmers,

I try to create a map with leaflet directive. You can see the fiddle here.
fiddle
In the fiddle above, when i drag the map, the marker will always be in the center. But when i zoom in/out (using the scroll), the map is zooming to the area of my mouse, thus changing the coordinate of my marker.

What should i do to make the map zoom to my marker in the center of the map (and not changing the marker coordinate) when I zoom in/out?

Any help is appreciated :)

This is the js code:

var app = angular.module('demoapp', ['leaflet-directive']);

app.controller('DemoController', ['$scope', 'leafletData', function($scope, leafletData) {
  angular.extend($scope, {
    center: {
      lat: 51.505,
      lng: -0.09,
      zoom: 5
    },
    markers: {
      marker: {
        lat: 51.505,
        lng: -0.09,
        draggable: false
      }
    },
    defaults: {
      zoomControl: false
    }
  })

  $scope.$on('leafletDirectiveMap.move', function(event, args) {
    var map = args.leafletEvent.target;
    var center = map.getCenter();

    // Update the marker.
    $scope.markers = {
      marker: {
        draggable: false,
        lat: center.lat,
        lng: center.lng,
        draggable: false
      }
    };
  });
}]);

You can try this as a start fiddle :

var app = angular.module('demoapp', ['leaflet-directive']);

app.controller('DemoController', ['$scope', '$timeout', 'leafletData', function($scope, $timeout, leafletData) {
  angular.extend($scope, {
    center: {
      lat: 51.505,
      lng: -0.09,
      zoom: 5
    },
    markers: {
      marker: {
        lat: 51.505,
        lng: -0.09,
        draggable: false
      }
    },
    defaults: {
      dragging: false,
      scrollWheelZoom: false
    }
  });
}]);

And in your html be sure to pass the defaults:

<body ng-controller="DemoController">
  <leaflet defaults="defaults" center="center" markers="markers" defaults="defaults"></leaflet>
</body>

Now users can not zoom and drag with the mouse, only using the zoom controls which makes the map stay centered.

In the leaflet docs here they say, you can set scrollWheelZoom to 'center' , that would always zoom to the current center of the map (that should be what you want), but i could not get this to work on plunkr. Not sure why, maybe angular-leaflet is not supporting this feature?!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM