Jump to content

API Gmaps - Clustering de markers contenu dans une base de donnée MySQL


dav3net
Go to solution Solved by dav3net,

Recommended Posts

Bonjour,

Contexte : Utilisation d'un script d'annuaire en PHP MySQL avec un affichage d'une carte via API Gmaps et des coordonnées contenu dans une des table de la bd MySQL.

Pour cela j'ai suivi le tuto google pour afficher la carte suite à une génération d'une sortie au format KML/XML par un script PHP,

je vous laisse découvrir : https://developers.google.com/maps/articles/phpsqlajax_v3

Le code pour l'affichage de la carte est celui-ci :

<!DOCTYPE html >  <head>    <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />    <meta http-equiv="content-type" content="text/html; charset=UTF-8"/>    <title>PHP/MySQL & Google Maps Example</title>    <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js"></script>    <script type="text/javascript">    //<![CDATA[     var customIcons = {      restaurant: {        icon: 'http://labs.google.com/ridefinder/images/mm_20_blue.png'      },      bar: {        icon: 'http://labs.google.com/ridefinder/images/mm_20_red.png'      }    };     function load() {      var map = new google.maps.Map(document.getElementById("map"), {        center: new google.maps.LatLng(47.6145, -122.3418),        zoom: 13,        mapTypeId: 'roadmap'      });      var infoWindow = new google.maps.InfoWindow;       // Change this depending on the name of your PHP file      downloadUrl("phpsqlajax_genxml.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          });          bindInfoWindow(marker, map, infoWindow, html);        }      });    }     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() {}     //]]>   </script>   </head>   <body onload="load()">    <div id="map" style="width: 500px; height: 300px"></div>  </body> </html>

Je souhaiterais que les markers soit regroupés sous forme de clusters, j'ai trouvé la solution ici :

https://developers.google.com/maps/a...arkerclusterer
Les sources sur GitHUB
et plus d'exemples https://googlemaps.github.io/js-mark.../examples.html

Bref, en gros je pense qu'il faut intégrer le code suivant au précédent :

var center = new google.maps.LatLng(37.4419, -122.1419);var options = {'zoom': 13,'center': center,'mapTypeId': google.maps.MapTypeId.ROADMAP};var map = new google.maps.Map(document.getElementById("map"), options);var markers = [];for (var i = 0; i < 100; i++) {var latLng = new google.maps.LatLng(data.photos[i].latitude,data.photos[i].longitude);var marker = new google.maps.Marker({'position': latLng});markers.push(marker);}var markerCluster = new MarkerClusterer(map, markers);

Je ne maîtrise pas le JavaScript, et je n'arrive pas à compiler les deux fonctions... De l'aide serait la bienvenue.. Merci d'avance !

Link to comment
Share on other sites

var customIcons = {

restaurant: {

icon: 'http://labs.google.com/ridefinder/images/mm_20_blue.png'

},

bar: {

icon: 'http://labs.google.com/ridefinder/images/mm_20_red.png'

}

};

var aMarkers = [];

var clusterer = {};

function load() {

var map = new google.maps.Map(document.getElementById("map"), {

center: new google.maps.LatLng(47.6145, -122.3418),

zoom: 13,

mapTypeId: 'roadmap'

});

var infoWindow = new google.maps.InfoWindow;

// Change this depending on the name of your PHP file

downloadUrl("phpsqlajax_genxml.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

});

aMarkers.push(marker);

bindInfoWindow(marker, map, infoWindow, html);

clusterer = new MarkerClusterer(map, markers);

}

});

}

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

Absolument rien vérifié :)

Link to comment
Share on other sites

  • Solution

Merci Sstephane !!



Entre temps Google m'a répondu ici : https://code.google.com/p/gmaps-api-issues/issues/detail?id=8478&thanks=8478&ts=1439665354


(je n'ai pas réussi à faire fonctionner le code mis en réponse mais celui-ci est ok sur https://github.com/googlemaps/js-marker-clusterer/tree/gh-pages/examples)


Pour ceux à qui cela peut servir :



// Change this depending on the name of your PHP file
downloadUrl("phpsqlajax_genxml3.php", function(data) {
var xml = data.responseXML;
var clusteredmarkers = [];
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
});
clusteredmarkers.push(marker);
bindInfoWindow(marker, map, infoWindow, html);
}
var markerCluster = new MarkerClusterer(map,clusteredmarkers);//this also add the cluster to the map
});
}




Ne pas oublier d'initialiser le script de clustering :



<script>
var script = '<script type="text/javascript" src="src/markerclusterer';
if (document.location.search.indexOf('compiled') !== -1) {
script += '_compiled';
}
script += '.js"><' + '/script>';
document.write(script);
</script>




dont vous trouverez la source ici https://github.com/googlemaps/js-marker-clusterer


Bon dev à tous !

Link to comment
Share on other sites

Please sign in to comment

You will be able to leave a comment after signing in



Sign In Now
×
×
  • Create New...