Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to move the center position of google map

I am creating a google map in a script with the following code -

var mapElement,
    parent,
    mapOptions,
    map,
    marker,
    latLong,
    openMarker;

parent = document.getElementsByClassName('parent')[0];
mapElement = document.createElement('div');
latLong = new google.maps.LatLng(some_lat_from_db, some_long_from_db);

mapOptions = {
    center: latLong,
    zoom: 14,
    mapTypeId: google.maps.MapTypeId.ROADMAP
};

map = new google.maps.Map(mapElement, mapOptions);
marker = new google.maps.Marker({
    position: latLong,
    map: map,
    title: 'some title'
});

openMarker = function () {
    var infowindow = new google.maps.InfoWindow();
    infowindow.setContent('Some Content');
    infowindow.open(map, marker);
};

google.maps.event.addListener(marker, 'click', openMarker);
parent.appendChild(mapElement);
openMarker();

When using this code, the infowindow that opens up by default goes outside the map viewport, so it's not visible. I first tried to reduce the size of the info window but that didn't work out. So I thought to move the center of the map a bit so that the info window remains in the viewport.

So, how can I move the center by some pixels so that the info window remains in the viewport?

like image 654
MD Sayem Ahmed Avatar asked Jan 13 '13 17:01

MD Sayem Ahmed


People also ask

How do I center a Google map?

Please go to your map and drag and drop your map to the position you wish. You can also zoom in your map a little bit with mouse wheel or zoom cotrols on the bottom right corner of the map. Please remember to save your map after any changes. Hope that helps.

How do you move north on Google Maps?

Finding North Using Google Maps To do this, tap the compass icon in the top-right corner of the Google Maps map view. Your map position will move, with the icon updating to show that you're pointing north.


2 Answers

You can use .setCenter() to move the center of the map

map.setCenter(marker.getPosition());

Update

Convert the LatLng with .fromLatLngToDivPixel() into a Point add an offset and convert it back into a LatLng with .fromDivPixelToLatLng()

like image 69
Andreas Avatar answered Oct 09 '22 09:10

Andreas


forget all that crap this is what works if you want to reuse a google map marker or move a google map marker, or recenter a google map marker.

var lo = <yourval>;
var la = <yourval>;
var midpoint = {lat:la, lng:lo };
marker.setPosition(midpoint);

if you want to destroy a google maps marker or delete a google maps marker

marker.setMap(null);
like image 36
Michael Nelles Avatar answered Oct 09 '22 09:10

Michael Nelles