0

I'm trying to create an application in php that displays several markers on google map and allow a user to get the nearest marker when he click anywhere on the map. I tried the following code. But its not working. Can anyone please help?

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml">
<head> 
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" /> 
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/> 
    <title>Google Maps Javascript API v3 Example: Loading clustered data from an XML</title> 
<script type="text/javascript" src="http://maps.google.com/maps/api/js?libraries=geometry&sensor=false"></script> 
<style type="text/css">
html, body { height: 100%; } 
</style>
<script type="text/javascript"> 
//<![CDATA[

      var side_bar_html = ""; 
      var gmarkers = []; 
      var map = null;
      var markerclusterer = null;

function createMarker(latlng, name, html) {
    var contentString = html;
    var marker = new google.maps.Marker({
        position: latlng,
        // map: map,
        zIndex: Math.round(latlng.lat()*-100000)<<5
        });

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

    gmarkers.push(marker);

    side_bar_html += '<a href="javascript:myclick(' + (gmarkers.length-1) + ')">' + name + '<\/a><br>';
}

function myclick(i) {
  google.maps.event.trigger(gmarkers[i], "click");
}

function initialize() {

var myOptions = {
    zoom: 12,
    center: new google.maps.LatLng(8.491118,76.949840),
    mapTypeControl: true,
    mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU},
    navigationControl: true,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  }
  map = new google.maps.Map(document.getElementById("map_canvas"),
                            myOptions);
      google.maps.event.addListener(map, 'click', function() {
        infowindow.close();
        });

  google.maps.event.addListener(map, 'click', find_closest_marker);

  downloadUrl("marker.xml", function(doc) {
  map.markers = [];
        var xmlDoc = xmlParse(doc);
        var markers = xmlDoc.documentElement.getElementsByTagName("marker");
        for (var i = 0; i < markers.length; i++) {

          var lat = parseFloat(markers[i].getAttribute("Lat"));
          var lng = parseFloat(markers[i].getAttribute("Longt"));
          var point = new google.maps.LatLng(lat,lng);

          var hname = markers[i].getAttribute("Hname");
              var Phone = markers[i].getAttribute("Phone");

          var html="<b>"+hname+"</b><br>"+Phone;

          var marker = createMarker(point,hname+" "+Phone,html);
        }
        markerCluster = new MarkerClusterer(map, gmarkers);
        document.getElementById("side_bar").innerHTML = side_bar_html;
      });
    }

var infowindow = new google.maps.InfoWindow(
  { 
    size: new google.maps.Size(150,50)
  });

function find_closest_marker( event ) {
    var closestMarker = -1;
    var closestDistance = Number.MAX_VALUE;
    for( i=0;i<gmarkers.length; i++ ) {
        var distance = google.maps.geometry.spherical.computeDistanceBetween(gmarkers[i].getPosition(),event.latLng);
        if ( distance < closestDistance ) {
            closestMarker = i;
            closestDistance = distance;
        }
    }
    map.setCenter(gmarkers[closestMarker].getPosition());
    if (map.getZoom() < 16) map.setZoom(16);
    google.maps.event.trigger(gmarkers[closestMarker], 'click');
}


    </script> 
  </head> 
<body style="margin:0px; padding:0px;" onload="initialize()">     
<table border="1"> 
      <tr> 
        <td> 
           <div id="map_canvas" style="width: 550px; height: 450px"></div> 
        </td> 
        <td valign="top" > 
           <div id="side_bar" style="width:300px;height:450px; text-decoration: underline; color: #4444ff; overflow:auto;"></div> 
        </td> 
      </tr> 
    </table> 
   </body> 
</html> 

marker.xml

<markers>
<marker Hname="CHC Anchuthengu" Lat="8.6734310" Longt="76.7581770"/>
<marker Hname="PHC Perumathura" Lat="8.6218640" Longt="76.7975220"/>
<marker Hname="PHC Keezhattingal" Lat="8.6982130" Longt="76.7915000"/>
<marker Hname="PHC Azhoor" Lat="8.6408080" Longt="76.8252470"/>
</markers>
JeNy
  • 87
  • 2
  • 5
  • 13
  • What isn't working? What happened? What did you expect? – Patrick Kostjens Aug 10 '13 at 10:07
  • 1
    Actually, the page displays google map with all markers (from database) . But what I need is to alert the nearest marker, when a user clicks anywhere on the map. – JeNy Aug 10 '13 at 10:17
  • You are using the Google Maps API v3, not the deprecated Google Maps API v2, changed the tag to reflect that. – geocodezip Aug 10 '13 at 16:32

1 Answers1

1

You need to create the map.markers array (this part not tested):

 downloadUrl("phpsqlajax_genxml.php", function(data) {
    map.markers = [];
    var xml = data.responseXML;
    var markers = xml.documentElement.getElementsByTagName("marker");
    for (var i = 0; i < markers.length; i++) {
      var hname = markers[i].getAttribute("Hname");
      var Phone = markers[i].getAttribute("Phone");
      var point = new google.maps.LatLng(parseFloat(markers[i].getAttribute("Lat")), parseFloat(markers[i].getAttribute("Longt")));
      var html = "<b>" + hname + "<br/>" + Phone + "</b>";
    var type = "bar";
      var icon = customIcons[type] || {};
      var marker = new google.maps.Marker({
        map: map,
        position: point,
        icon: icon.icon,
        shadow: icon.shadow
      });
      map.markers.push(marker);
      bindInfoWindow(marker, map, infoWindow, html);
    }
  });

I would suggest using the geometry library computeDistanceBetween function

function find_closest_marker( event ) {
    var closestMarker = -1;
    var closestDistance = Number.MAX_VALUE;
    for( i=0;i<map.markers.length; i++ ) {
        var distance = google.maps.geometry.spherical.computeDistanceBetween(gmarkers[i].getPosition(),event.latLng);
        if ( distance < closestDistance ) {
            closestMarker = i;
            closestDistance = distance;
        }
    }
    allert(map.markers[closestMarker].title);
}

working example

geocodezip
  • 158,664
  • 13
  • 220
  • 245
  • Thank you so much for the working example. I tried to change the code as you said above(using the geometry library computeDistanceBetween function). But it didn't work. So, I just changed the whole code as given in your example. But now, the problem is that the sidebar and markers are not shown in the map. Side bar is left blank. The changed code is given above. Please help me to figure out where the problem is – JeNy Aug 11 '13 at 08:38
  • If you want my help determining why your copy of my code doesn't work, provide a link to a live version that exhibits the problem. – geocodezip Aug 11 '13 at 15:55
  • I've uploaded the code and xml file in google drive. Please check out this link : https://drive.google.com/folderview?id=0Bx_RFu3eZf9fcVdNOW80NUlNeTQ&usp=sharing – JeNy Aug 13 '13 at 06:17
  • Live version : http://gmeg.webuda.com/google3.php – JeNy Aug 13 '13 at 06:56
  • Your "live version" has javascript errors: `Uncaught SyntaxError: Unexpected token < error404.000webhost.com/?:1`, `Uncaught ReferenceError: downloadUrl is not defined google3.php:71` and your XML is not valid (it is missing the closing `` tag – geocodezip Aug 13 '13 at 12:36
  • Cheers for the working example. Able to slot it into my code with minimum fuss. – Craicerjack Feb 17 '15 at 15:31