简体   繁体   中英

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?

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()

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);

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