beluga.me beluga.me - 1 month ago 15
Javascript Question

Google Maps: Calculate position not covered by div overlay

Following situation:


  • My google maps div occupies the entire screen (100% width and height)

  • A button toggles the visibility of a div overlay (sidebar) that occupies the right side of the map

  • A marker is on the map that can get hidden underneath the white overlay

  • To avoid the marker being hidden I want to move the map to the right so that the marker is visible in the center of the yellow area left of the box

  • The page is bootstrap+angular based



enter image description here

The collision check box vs. marker is not the problem, but I can't get it to work to move the map accordingly.

This is what I tried:

google.maps.event.addListenerOnce($scope.map, "projection_changed", function() {
$scope.projection = $scope.map.getProjection();
});

var sidebar = document.getElementById('sidebar');
var rect = sidebar.getBoundingClientRect();

var marker = $scope.mainmarker.getPosition();
marker = $scope.projection.fromLatLngToPoint(marker);
marker.x = rect.left / 2;
marker = $scope.projection.fromPointToLatLng(marker);
$scope.map.setCenter(marker);


But from what I see the map is moved way too far.

Answer

I settled with this solution that works quite well for me:

   if (underneath === true) {
        var marker = $scope.mainmarker.getPosition();
        var pixelpoint = $scope.projection.fromLatLngToPoint(point);
        pixelpoint.x += 250 / Math.pow(2, $scope.map.getZoom());
        point = $scope.projection.fromPointToLatLng(pixelpoint);
        $scope.map.setCenter(point);
    }
Comments