简体   繁体   中英

Google Maps V3 (PHP/MYSQL with custome infobox)

I'm using google maps with PHP/MSQL, i've read the documentation on google and take the code from there.

I want to display custom box like this example . Everything works fine with my code, except for the text inside the box, i've always the text that is actually the last entry on my database... how to manage this?

var customIcons = {
  0: {
    icon: 'gif_blue.gif',
    shadow: 'gif_blue.gif'
  },
  1: {
    icon: 'gif_green.gif',
    shadow: 'gif_green.gif'
  }
};

function initialize() {
  var map = new google.maps.Map(document.getElementById("map_canvas"), {
    center: new google.maps.LatLng(51.5001524,  -0.1262362),
    zoom: 14,
    mapTypeId: 'terrain'
  });

  // Change this depending on the name of your PHP file
  downloadUrl("xml.php", function(data) {
    var xml = data.responseXML;
    var markers = xml.documentElement.getElementsByTagName("marker");
    for (var i = 0; i < markers.length; i++) {
      var name = markers[i].getAttribute("name");
      var address = markers[i].getAttribute("address");
      var type = markers[i].getAttribute("type");
      var point = new google.maps.LatLng(
          parseFloat(markers[i].getAttribute("lat")),
          parseFloat(markers[i].getAttribute("lng")));
      //var html = "<b>" + name + "</b> <br/>" + address;
      var icon = customIcons[type] || {};
      var marker = new google.maps.Marker({
        map: map,
        position: point,
        icon: icon.icon,
        shadow: icon.shadow
      });




    var boxText = document.createElement("div");
    boxText.style.cssText = "border: 1px solid black; margin-top: 8px; background: yellow; padding: 5px;";
    boxText.innerHTML = "Nom : <b>" + name + "</b> <br/>Adresse :" + address + "</b> <br/>Type :" + type;

    var myOptions = {
             content: boxText
            ,disableAutoPan: false
            ,maxWidth: 0
            ,pixelOffset: new google.maps.Size(-140, 0)
            ,zIndex: null
            ,boxStyle: { 
              background: "url('tipbox.gif') no-repeat"
              ,opacity: 0.75
              ,width: "280px"
             }
            ,closeBoxMargin: "10px 2px 2px 2px"
            ,closeBoxURL: "http://www.google.com/intl/en_us/mapfiles/close.gif"
            ,infoBoxClearance: new google.maps.Size(1, 1)
            ,isHidden: false
            ,pane: "floatPane"
            ,enableEventPropagation: false
    };

            var ib = new InfoBox(myOptions);
            //THE PROBLEM SHOULD BE HERE :
            google.maps.event.addListener(marker, 'click', (function(marker, i) {
            return function() {
              ib.open(map, marker);
            }
          })(marker, i));

    }

  });

}
function bindInfoWindow(marker, map, infoWindow, html) {
  google.maps.event.addListener(marker, 'click', function() {
    infoWindow.setContent(html);
    infoWindow.open(map, marker);
  });
}

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, request.status);
    }
  };

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

function doNothing() {}

The problem is that JavaScript does not have block scoping . All of the variables you declare in this loop:

for (var i = 0; i < markers.length; i++) {
    /* declarations here */
}

exist within the scope of the anonymous callback you have defined ( downloadUrl("xml.php", function(data) { /* ... */ } ). I see that you have tried to fix this problem with the immediate function invocation that you commented, but you didn't do it correctly.


This should work:

function initialize() {
    var map = new google.maps.Map(document.getElementById("map_canvas"), {
        center: new google.maps.LatLng(51.5001524, -0.1262362),
        zoom: 14,
        mapTypeId: 'terrain'
    });

    // Change this depending on the name of your PHP file
    downloadUrl("xml.php", function(data) {
        function createMarker(markerXML) {
            var name = markerXML.getAttribute("name"),
                address = markerXML.getAttribute("address"),
                type = markerXML.getAttribute("type"),
                lat = parseFloat(markerXML.getAttribute("lat")),
                lng = parseFloat(markerXML.getAttribute("lng")),

                icon = customIcons[type] || {},

                marker = new google.maps.Marker({
                    map: map,
                    position: new google.maps.LatLng(lat, lng),
                    icon: icon.icon,
                    shadow: icon.shadow
                }),

                boxText = document.createElement("div");

            boxText.style.cssText = "border: 1px solid black; margin-top: 8px; background: yellow; padding: 5px;";
            boxText.innerHTML = "Nom : <b>" + name + "</b> <br/>Adresse :" + address + "</b> <br/>Type :" + type;

            var myOptions = {
                content: boxText,
                disableAutoPan: false,
                maxWidth: 0,
                pixelOffset: new google.maps.Size(-140, 0),
                zIndex: null,
                boxStyle: {
                    background: "url('tipbox.gif') no-repeat",
                    opacity: 0.75,
                    width: "280px"
                },
                closeBoxMargin: "10px 2px 2px 2px",
                closeBoxURL: "http://www.google.com/intl/en_us/mapfiles/close.gif",
                infoBoxClearance: new google.maps.Size(1, 1),
                isHidden: false,
                pane: "floatPane",
                enableEventPropagation: false
            };

            var infoBox = new InfoBox(myOptions);

            google.maps.event.addListener(marker, 'click', function () {
                    infoBox.open(map, marker);
                }
            });
        }

        var xml = data.responseXML,
            markers = xml.documentElement.getElementsByTagName("marker"),
            numMarkers = markers.length;

        for (var i = 0; i < numMarkers; i++) {
            createMarker(markers[i]);
        }
    });
}

Aside from a couple of small stylistic and performance tweaks, the only things I changed were:

  1. Breaking the logic in your for loop out into a separate function
  2. Removing the pointless immediate function invocation in google.maps.event.addListener

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