How to move the center position of google map

女生的网名这么多〃 提交于 2020-01-02 02:32:27

问题


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?


回答1:


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




回答2:


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


来源:https://stackoverflow.com/questions/14305876/how-to-move-the-center-position-of-google-map

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!