简体   繁体   中英

Google map not centering in Firefox

I've got a strange issue with a google map, which I can only duplicate in Firefox. To explain, we have a static map which when clicked on enlarges to a full interactable map with a marker in the center. This works fine in all browsers, except Firefox. In Firefox, what happens is the map is not centered correctly. The marker is placed, however, it is in the top left corner of the map just outside of the visible area.

Any ideas? This has been baffling me for a while.

JavaScript:

// lat and lng are initialized earlier
var latlng = new google.maps.LatLng(lat, lng);
var myOptions = {
    zoom: 13,
    center: latlng,
    mapTypeId: google.maps.MapTypeId.ROADMAP,
};

var map = new google.maps.Map($("#map_canvas")[0], myOptions);

var marker = new google.maps.Marker({
    position: latlng,
    map: map,
    icon: icon
});

var resizeMap = function () {
    $("#smallMap, #smallMapOverlay").remove();
    $("#map_canvas").show();
    google.maps.event.trigger(map, 'resize');
    map.setCenter(latlng, 13);
};

$("#smallMapOverlay").live("click", function (e) {
    e.preventDefault();
    resizeMap();
});

CSS:

#map_canvas {
    width: 640px;
    height: 377px; 
}

Karim79' fix works. I worked it out in a slightly different way. If you have a wrapper class to handle mapping functions, you could create a reset function like so,

function reset(){
        setTimeout(function(){gm.event.trigger(_gMap, 'resize');}, 50);
        setTimeout(function(){_gMap.setCenter(settings.mapOptions.center);}, 100);
    }

Best

It seems that putting the resize and setCenter methods into show() 's callback, and giving a tiny delay fixes the issue.

var resizeMap = function () {
    $("#smallMap, #smallMapOverlay").remove();
    $("#map_canvas").show(10, function () {
        google.maps.event.trigger(map, 'resize');
        map.setCenter(latlng, 13);
    });
};

It's not the most elegant solution, but it works.

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