سؤال

I am trying to use the following lines of code to fit the map bounds to the markers:

var latlngbounds = new google.maps.LatLngBounds();
latlngbounds.extend(latlng);    
map.fitBounds(latlngbounds);    

For some reason the map zooms to location 0,0 on the map.

Update 1: Seems to be working in IE9, but not in Chrome. Get the following error message in Chrome Developer mode: Port error: Could not establish connection. Receiving end does not exist.

Update 2: After reloading the page in IE9 it also stopped working.

Here is my code. I must be doing something basic wrong?

//variables
var map;
var markers = [];
var latlngbounds;
//initialize google map
function initialize()
{
    var myOptions = {
        center: new google.maps.LatLng(-26.17706, 28.34613),
        zoom: 10,
        mapTypeId: google.maps.MapTypeId.ROADMAP};

    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
    latlngbounds = new google.maps.LatLngBounds();

    //display markers
    updateMarkersDisplayed(); 
}

//displays google map after site load complete
google.maps.event.addDomListener(window, 'load', initialize);

//retrieves markers for map
function updateMarkersDisplayed()
{
    //php get url
    var searchUrl = 'getCoords.php';

    downloadUrl(searchUrl, function(data) {
        var xml = parseXml(data);   
        var markerNodes = xml.documentElement.getElementsByTagName("marker");
        for (var i = 0; i < markerNodes.length; i++) {
            var id = markerNodes[i].getAttribute("device_id");
            var latlng = new google.maps.LatLng(
                parseFloat(markerNodes[i].getAttribute("lat")),
                parseFloat(markerNodes[i].getAttribute("lng")));

            createMarker(latlng, id);      
            latlngbounds.extend(latlng);    
        }
    }); 
    //zoom map to display all markers
    map.fitBounds(latlngbounds);    
}

//create marker and display on map if not already visible
function createMarker(latlng, id) {      

    var iconUrl = 'images/phones.png';              
    var marker = new google.maps.Marker({
        map: map,
        position: latlng,
        title: id,
        icon: iconUrl
    });     

    markers.push(marker);   
    markers[markers.length-1].setMap[map];

}

//download xml file containing markers specified by the GET parameters contained in the url passed
function downloadUrl(url,callback)
{
    var request = window.ActiveXObject ?
        new ActiveXObject('Microsoft.XMLHTTP') :
        new XMLHttpRequest();

    request.onreadystatechange = function() {
        if (request.readyState == 4) 
        {
            request.onreadystatechange = doNothing;
            callback(request.responseText, request.status);
        }
    };

    request.open('GET', url, true);
    request.send(null);
}

//parse text returned by php script
function parseXml(str) {
    if (window.ActiveXObject) 
    {
        var doc = new ActiveXObject('Microsoft.XMLDOM');
        doc.loadXML(str);
        return doc;
    } 
    else if (window.DOMParser) 
    {
        return (new DOMParser).parseFromString(str, 'text/xml');
    }
}

//capture extra XMLHttpRequest responses
function doNothing() {}
هل كانت مفيدة؟

المحلول 2

Had to move the map.fitBounds(latlngbounds); inside the downloadUrl(searchUrl, function(data) { function as the fitBounds was being called before the XML download was completed.

    downloadUrl(searchUrl, function(data) {
        var xml = parseXml(data);   
        var markerNodes = xml.documentElement.getElementsByTagName("marker");
        for (var i = 0; i < markerNodes.length; i++) {
            var id = markerNodes[i].getAttribute("device_id");
            var latlng = new google.maps.LatLng(
                parseFloat(markerNodes[i].getAttribute("lat")),
                parseFloat(markerNodes[i].getAttribute("lng")));

            bounds.extend(latlng);      
            createMarker(latlng, id);           
        }
        //zoom map to display all markers
        map.fitBounds(bounds);
    });     

نصائح أخرى

A google.maps.LatLngBounds that centers the map on 0,0 is a symptom of an empty bounds.

You are using XML for your marker data. The browsers that don't work probably don't like your XML, try pointing those browsers directly at the XML feed and fixing any problems reported.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top