[working] google map api v3 infowindow custom positioning based on space from top, left, right, bottom

So in this post I’m going to share another real experience with google map api v3. So I was working on google map api and I had a challenge to show the infowindow on marker hover. It wasn’t too difficult as google has great tutorial about all that.

But the real challenge was to show the info window based on the space from the top, left, right and bottom. So I spend a few hours on this and wasn’t able to figure out how to do it. Actually google do it default but in that case our map was moving down. I fixed that using set disableAutoPan: true like below sample code.

var infowindow = new google.maps.InfoWindow({
    disableAutoPan: true
});

With that the map wasn’t moving down but the info window wasn’t showing full. Please check below image.

How to stop google map moving down, when info window shown

Please find below code to fix stop google map move down.

 google.maps.event.addListener(marker, 'mouseover', function () {
                infowindow.setOptions({ pixelOffset: self.getInfowindowOffset(self.map, marker) });
                infowindow.setContent(windowContent);
                //infowindow.setPosition(marker.getPosition());
                infowindow.open(map, this);          
        });
getInfowindowOffset = function (map, marker) {
        var center = this.getPixelFromLatLng(map.getCenter()),
            point = this.getPixelFromLatLng(marker.getPosition()),
            quadrant = "",
            offset;
        quadrant += (point.y > center.y) ? "b" : "t";
        quadrant += (point.x < center.x) ? "l" : "r";
        if (quadrant == "tr") {
            offset = new google.maps.Size(-160, 250);
        } else if (quadrant === "tl") {
            offset = new google.maps.Size(160, 260);
        } else if (quadrant === "br") {
            offset = new google.maps.Size(-140, 30);
        } else if (quadrant === "bl") {
            offset = new google.maps.Size(160, 30);
        }
        return offset;
    };

    getPixelFromLatLng = function (latLng) {
        var projection = this.map.getProjection();
        var point = projection.fromLatLngToPoint(latLng);
        return point;
    };

This worked perfect for me, Now It will auto adjust the info window position based on space available from the top left, top right, bottom left, bottom right etc.

Please find below working example picture.

If it work for you guys, don't forgot to comment.

Cheers..

Posted by | View Post | View Group