On my website I have a form that allows users to register. It asks users to provide their city, state, and country. I also have a map that drops a marker for each user based on a lat/lng that's drawn from that city, state, country combination ($location).
Because I'm not being super specific (as in, I'm not asking for their ACTUAL address), I have a number of users that have the same lat/lng. And this creates a problem when trying to view markers on my map.
Should I use a clustering service? If so, do you have any suggestions?? Like I said, information flows from mySQL database --> XML --> PHP.
If so, it'll be clustered at the most zoomed level (like I said, same lat/lng). As a result, I'm going to need a info window that allows me to select each user at that particular location.
Ideas? Suggestions??? Much appreciated!!!
Jeremy
MarkerClusterer: http://gmaps-utility-library.googlecode.com/svn/trunk/markerclusterer/1.0/docs/examples.html
Or by hand (roughly - sample code only!)
var latlng = new google.maps.LatLng(-33.8671390, 151.2071140);
var myOptions = {
zoom: 8,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var markers = [];
var newmarkers = [];
for(var j=0; j<5; j++) {
markers.push({lat:-33.8671390, lng:151.2071140, title:'This is marker #' + i });
if(j==0) newmarkers.push(markers[j]);
for(var i=0; i<newmarkers.length; i++) {
if(newmarkers[i].lat == markers[j].lat && newmarkers[i].lng == markers[j].lng) {
newmarkers[i].title += ' AND ' + markers[j].title;
continue;
}
newmarkers.push(markers[j]);
}
}
for(var i=0; i<newmarkers.length; i++) {
var mkr = new google.maps.Marker({
position: new google.maps.LatLng(newmarkers[i].lat, newmarkers[i].lng),
map: map,
title: newmarkers[i].title
});
}
Thought I'd paste my code:
function load() {
if (GBrowserIsCompatible()) {
var map = new GMap2(document.getElementById("map"));
map.addControl(new GSmallMapControl());
map.addControl(new GMapTypeControl());
map.setCenter(new GLatLng(47.614495, -122.341861), 2);
map.enableScrollWheelZoom();
GDownloadUrl("world_xml.php", function(data) {
var xml = GXml.parse(data);
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var first_name = markers[i].getAttribute("first_name");
var last_name = markers[i].getAttribute("last_name");
var email = markers[i].getAttribute("email");
var affiliation = markers[i].getAttribute("affiliation");
var status = markers[i].getAttribute("status");
var service = markers[i].getAttribute("service");
var rank = markers[i].getAttribute("rank");
var specialty = markers[i].getAttribute("specialty");
var city = markers[i].getAttribute("city");
var state = markers[i].getAttribute("state");
var country = markers[i].getAttribute("country");
var point = new GLatLng(parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var marker = createMarker(point, rank, first_name, last_name, email, affiliation, status, service, specialty, city, state, country);
map.addOverlay(marker);
}
});
}
}
function createMarker(point, rank, first_name, last_name, email, affiliation, status, service, specialty, city, state, country) {
var marker = new GMarker(point);
var html = "" + rank + " " + first_name + " " + last_name + " " + service + ", " + status + " " + specialty + " " + affiliation + " " + city + ", " + state + " " + country + " " + email + " " + " ";
GEvent.addListener(marker, 'click', function() {
marker.openInfoWindowHtml(html);
});
return marker;
}
Related
I have plotted over a thousand markers on a map from a mysql database. This page map.php takes an xml and grabs the information. Within this array, several points have multiple entries in the database, but google maps only shows the infowindow for the most recent marker plotted.
I'd like the infowindow to list all for that locations, similar to how a loop would work in php. So everything that shares a lat and a long would be within the one info window
The code i use:
downloadUrl("map/map_data_source.php", function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var date = markers[i].getAttribute("date");
var artist = markers[i].getAttribute("artist");
var venue = markers[i].getAttribute("venue");
var address = markers[i].getAttribute("address");
var city = markers[i].getAttribute("city");
var idgigs = markers[i].getAttribute("id");
var country = markers[i].getAttribute("country");
var count = markers[i].getAttribute("count");
var swith = markers[i].getAttribute("swith");
var stage = markers[i].getAttribute("stage");
var type = markers[i].getAttribute("type");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var html =
'<div id="infoWindow" width="600px"><img src="projects/components/' + artist + '">' +
'<br><br>' + date +
'<br><b>' + venue + '</b> / ' + city + '<br>' + swith + stage +
'<br><b><a class="second_sub_menu" href="../projects/bands.php?sub=Setlist&info=' + artist + '&id=' + idgigs + '">SHOW INFORMATION</a></b>';
var marker = new google.maps.Marker({
map: map,
position: point,
icon: 'http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=' + count + '|' + type + '|000000',
zIndex: i
});
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);
if (map.getZoom() < 4) map.setCenter(marker.getPosition());
if (map.getZoom() < 4) map.setZoom(4);
});
google.maps.event.addListener(map, "click", function() {infoWindow.close();});
}
So this question has appeared a million and one times, but there still appears to be no real answer.. (There are mentions to markclusters and spiderers as another way of showing these results, but I want the markers how they are)..
Thank you mucho in advance, I have progressed well, but without this bit working, the project may as well be binned..! :(
Using #Dr.Molle link i got it working, in case anyone is after this feature, this is my new code
var markerContents={};
var infoWindow = new google.maps.InfoWindow;
downloadUrl("map/map_data_source.php", function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var date = markers[i].getAttribute("date");
var artist = markers[i].getAttribute("artist");
var venue = markers[i].getAttribute("venue");
var address = markers[i].getAttribute("address");
var city = markers[i].getAttribute("city");
var idgigs = markers[i].getAttribute("id");
var country = markers[i].getAttribute("country");
var count = markers[i].getAttribute("count");
var swith = markers[i].getAttribute("swith");
var stage = markers[i].getAttribute("stage");
var type = markers[i].getAttribute("type");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var customIcons = {
FFFFFF: {
icon: 'http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=' + count + '|' + type + '|000000'
},
upcoming: {
icon: '../map/marker/orange.png'
}
};
var markerId = point.toString();
if(!markerContents[markerId]){
markerContents[markerId] = [];
}
var html =
'<div id="infoWindow" width="600px"><img src="projects/components/' + artist + '">' +
'<br><br>' + date +
'<br><b>' + venue + '</b> / ' + city + '<br>' + swith + stage +
'<br><b><a class="second_sub_menu" href="../projects/bands.php?sub=Setlist&info=' + artist + '&id=' + idgigs + '">SHOW INFORMATION</a></b>';
var icon = customIcons[type] || {};
markerContents[markerId].push(html);
var marker = new google.maps.Marker({
map: map,
position: point,
zIndex: i,
icon: icon.icon
});
bindInfoWindow(marker, map, infoWindow, markerContents[markerId]);
}
});
}
function bindInfoWindow(marker, map, infoWindow, html) {
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(html.join('<hr/>'));
infoWindow.open(map, marker);
if (map.getZoom() < 4) map.setCenter(marker.getPosition());
if (map.getZoom() < 4) map.setZoom(4);
});
google.maps.event.addListener(map, "click", function() {infoWindow.close();});
}
Because i wanted custom icons and I wanted a select group of markers to always be at the top, i had to modify the icons code too, but it works. So thank you to those that helped
I am trying to place markers where the cities in a mySQL database are. The page loads but it shows "map div" where the map should load. I am not sure what is wrong. Thank you for taking a look and trying to help!
<script type="text/javascript">
var directionDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer();
var mapOptions = {
zoom: 5,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map_canvas'),
mapOptions);
directionsDisplay.setMap(map);
//create an array of latitudes, longitudes, and city names
var markers = [
<?php
//orgnize fans by city
$query = "SELECT city, state, COUNT(*) fans FROM users GROUP BY city ORDER BY fans DESC";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
//pulls the city, state code from the database and stores it as a string in $address
$address = urlencode('"' . $row['city'] . ", " . $row['state'] . '"');
$googleApi = 'http://maps.googleapis.com/maps/api/geocode/json?address=%s&sensor=false';
$json = file_get_contents(sprintf($googleApi, $address));
$resultObject = json_decode($json);
$location = $resultObject->results[0]->geometry->location;
$lat = $location->lat;
$lng = $location->lng;
echo "{ lat: ".$lat.", lng: ".$lng.", name: ".'"'.$row['city'].", ".$row['state'].'"'."},";
}
?>
];
// Create the markers ad infowindows.
for (index in markers) addMarker(markers[index]);
function addMarker(data) {
// Create the marker
var marker = new google.maps.Marker({
position: new google.maps.LatLng(data.lat, data.lng),
map: map,
title: data.name
});
// Create the infowindow with two DIV placeholders
// One for a text string, the other for the StreetView panorama.
var content = document.createElement("DIV");
var title = document.createElement("DIV");
title.innerHTML = data.name;
content.appendChild(title);
var streetview = document.createElement("DIV");
streetview.style.width = "200px";
streetview.style.height = "200px";
content.appendChild(streetview);
var infowindow = new google.maps.InfoWindow({
content: content
});
// Open the infowindow on marker click
google.maps.event.addListener(marker, "click", function() {
infowindow.open(map, marker);
});
// Handle the DOM ready event to create the StreetView panorama
// as it can only be created once the DIV inside the infowindow is loaded in the DOM.
google.maps.event.addListenerOnce(infowindow, "domready", function() {
var panorama = new google.maps.StreetViewPanorama(streetview, {
navigationControl: false,
enableCloseButton: false,
addressControl: false,
linksControl: false,
visible: true,
position: marker.getPosition()
});
});
}
// Try HTML5 geolocation
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
var infowindow = new google.maps.InfoWindow({
map: map,
position: pos,
content: 'Your Current City'
});
map.setCenter(pos);
}, function() {
handleNoGeolocation(true);
});
} else {
// Browser doesn't support Geolocation
handleNoGeolocation(false);
}
}
function handleNoGeolocation(errorFlag) {
if (errorFlag) {
var content = 'Error: The Geolocation service failed.';
} else {
var content = 'Error: Your browser doesn\'t support geolocation.';
}
var options = {
map: map,
position: new google.maps.LatLng(60, 105),
content: content
};
var infowindow = new google.maps.InfoWindow(options);
map.setCenter(options.position);
}
function calcRoute() {
var start = document.getElementById('start').value;
var end = document.getElementById('end').value;
var waypts = [];
var checkboxArray = document.getElementById('waypoints');
for (var i = 0; i < checkboxArray.length; i++) {
if (checkboxArray.options[i].selected == true) {
waypts.push({
location:checkboxArray[i].value,
stopover:true});
}
}
var request = {
origin: start,
destination: end,
waypoints: waypts,
optimizeWaypoints: true,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
var route = response.routes[0];
var summaryPanel = document.getElementById('directions_panel');
summaryPanel.innerHTML = '';
// For each route, display summary information.
for (var i = 0; i < route.legs.length; i++) {
var routeSegment = i + 1;
summaryPanel.innerHTML += '<b>Route Segment: ' + routeSegment + '</b><br>';
summaryPanel.innerHTML += route.legs[i].start_address + ' to ';
summaryPanel.innerHTML += route.legs[i].end_address + '<br>';
summaryPanel.innerHTML += route.legs[i].distance.text + '<br><br>';
}
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
When I open the html, I call initialize and make the canvas:
<body onload="initialize()">
<div id="map_canvas" style="width: 1100px; height: 450px;">map div</div>
I am trying to make an array of latitudes and longitudes using cities that I have in a mySQL database. This is what I have so far. I am trying to set up the array variable in javascript, and echo out the fields inside. The "markers" array is read to make markers appear on the google map at the desired locations:
EDIT: Here is the entire script
<script type="text/javascript">
var directionDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer();
var mapOptions = {
zoom: 5,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map_canvas'),
mapOptions);
directionsDisplay.setMap(map);
var markers = [
<?php
//orgnize fans by city
$query = "SELECT city, state, COUNT(*) fans FROM users GROUP BY city ORDER BY fans DESC";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
//pulls the city, state code from the database and stores it as a string in $address
$address = urlencode('"' . $row['city'] . ", " . $row['state'] . '"');
$googleApi = 'http://maps.googleapis.com/maps/api/geocode/json?address=%s&sensor=false';
$json = file_get_contents(sprintf($googleApi, $address));
$resultObject = json_decode($json);
$location = $resultObject->results[0]->geometry->location;
$lat = $location->lat;
$lng = $location->lng;
echo "{ lat: ".$lat.", lng: ".$lng.", name: ".'"'.$row['city'].", ".$row['state'].'"'."},";
}
?>
];
// Create the markers ad infowindows.
for (index in markers) addMarker(markers[index]);
function addMarker(data) {
// Create the marker
var marker = new google.maps.Marker({
position: new google.maps.LatLng(data.lat, data.lng),
map: map,
title: data.name
});
// Create the infowindow with two DIV placeholders
// One for a text string, the other for the StreetView panorama.
var content = document.createElement("DIV");
var title = document.createElement("DIV");
title.innerHTML = data.name;
content.appendChild(title);
var streetview = document.createElement("DIV");
streetview.style.width = "200px";
streetview.style.height = "200px";
content.appendChild(streetview);
var infowindow = new google.maps.InfoWindow({
content: content
});
// Open the infowindow on marker click
google.maps.event.addListener(marker, "click", function() {
infowindow.open(map, marker);
});
// Handle the DOM ready event to create the StreetView panorama
// as it can only be created once the DIV inside the infowindow is loaded in the DOM.
google.maps.event.addListenerOnce(infowindow, "domready", function() {
var panorama = new google.maps.StreetViewPanorama(streetview, {
navigationControl: false,
enableCloseButton: false,
addressControl: false,
linksControl: false,
visible: true,
position: marker.getPosition()
});
});
}
// Try HTML5 geolocation
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
var infowindow = new google.maps.InfoWindow({
map: map,
position: pos,
content: 'Your Current City'
});
map.setCenter(pos);
}, function() {
handleNoGeolocation(true);
});
} else {
// Browser doesn't support Geolocation
handleNoGeolocation(false);
}
}
function handleNoGeolocation(errorFlag) {
if (errorFlag) {
var content = 'Error: The Geolocation service failed.';
} else {
var content = 'Error: Your browser doesn\'t support geolocation.';
}
var options = {
map: map,
position: new google.maps.LatLng(60, 105),
content: content
};
var infowindow = new google.maps.InfoWindow(options);
map.setCenter(options.position);
}
function calcRoute() {
var start = document.getElementById('start').value;
var end = document.getElementById('end').value;
var waypts = [];
var checkboxArray = document.getElementById('waypoints');
for (var i = 0; i < checkboxArray.length; i++) {
if (checkboxArray.options[i].selected == true) {
waypts.push({
location:checkboxArray[i].value,
stopover:true});
}
}
var request = {
origin: start,
destination: end,
waypoints: waypts,
optimizeWaypoints: true,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
var route = response.routes[0];
var summaryPanel = document.getElementById('directions_panel');
summaryPanel.innerHTML = '';
// For each route, display summary information.
for (var i = 0; i < route.legs.length; i++) {
var routeSegment = i + 1;
summaryPanel.innerHTML += '<b>Route Segment: ' + routeSegment + '</b><br>';
summaryPanel.innerHTML += route.legs[i].start_address + ' to ';
summaryPanel.innerHTML += route.legs[i].end_address + '<br>';
summaryPanel.innerHTML += route.legs[i].distance.text + '<br><br>';
}
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
When I open the html, I call initialize and make the canvas:
<body onload="initialize()">
<div id="map_canvas" style="width: 1100px; height: 450px;">map div</div>
You have a typo: sometimes you use long, at other times lng.
in the code segment:
var marker = new google.maps.Marker({
position: new google.maps.LatLng(data.lat, data.lng),
map: map,
title: data.name
});}
while earlier you use
$lng = $location->lng;
echo "{ lat: ".$lat.", lng: ".$long.", name: ".'"'.$row['city'].", ".$row['state'].'"'."},";
In effect, your echo statement, which should be producing longitudes in your array, is referencing a non-initialized variable, $long. Fix that and you should be good to go. In other words, change
$lng = $location->lng;
to
$long = $location->lng;
(or change your echo statement...)
My earlier answer dealt with the typo. I think there's a fundamental issue with "how to draw maps with the google API". The following code snippet (from google JavaScript API shows an example of using overlays (which is what a marker is):
var myLatlng = new google.maps.LatLng(-25.363882,131.044922);
var mapOptions = {
zoom: 4,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP, }
var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
var marker = new google.maps.Marker({
position: myLatlng,
title:"Hello World!" });
// To add the marker to the map, call setMap();
marker.setMap(map);
Several of these steps appear to be missing from your code - maybe you didn't show them, or maybe you didn't realize you needed them?
EDIT: even after you posted your full code, I still don't see certain things I would expect.
Here are one thing you can try for sure: call the google API before referencing it: add this line
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=false"> </script>
right below <head>, before your <script>
Fixing just this, and taking out a bunch of "superfluous" (for the purpose of "getting a map with a pin") lines, allowed me to create a simple file that can render a map of New York, NY with one marker on it. The source code can be found at http://www.floris.us/SO/maptest.php.txt . From there, you can add more stuff back in...
Further edit: with the lessons learnt, I made http://www.floris.us/SO/maptestFull.php which has most of the functionality you were looking for (not the DB lookup, which I don't have, obviously). Once again, source code is copied in .php.txt file so you can look at it. Slightly messy (from trying to turn things on/off) - you will have to look closely to see all the changes I made.
Edit:
I'm trying over the last couple of weeks to solve my problem. As I'm a True Beginner I'm learning the Code during the work Progress... I will try to clarify my question which hopefully show me the answer.
As i was asking before : I'm developing a web App based on Google maps API 3. A GPS-Logger is feeding a table on Mysql server with those values: id, latitude, longitude, date, time, userid. I want to create multiple unique Polylines. For each date group a new Polyline.
As I was saying, I've made some progress but I'm not quite sure that I'm on the right track.
Now I'm not sure what I'm getting it ether few Polylines that are connected making them into a big Polyline or Few Polylines on top of each others...
Another problem ist that with this code I can't seem to show the first "date-group Polyline".
I've Posted the Newer code Below the Original one and a >>jsfiddle<< link (although I didn't managed to get jsfiddle working on my side).
I assuming that this is no longer a Google-Maps question but I would be thankful if someone can help me to solve and understand it.
This is the code part I've posted before:
var map = new google.maps.Map(document.getElementById('map'), myOptions);
var infoWindow = new google.maps.InfoWindow;
// Change this depending on the name of your PHP file
downloadUrl("output-xml.php", function(data)
{
var points=[];
var markerbgn=[];
var markerend=[];
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++)
{
var date = markers[i].getAttribute("date");
var time = markers[i].getAttribute("time");
var timebgn = markers[0].getAttribute("time");
var timeend = markers[markers.length-1].getAttribute("time");
var type = markers[i].getAttribute("usid");
points[i] = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var html1 = "<b>" + date + "</b> <br/>" + timebgn + "</b> <br/>" + "Start Point";
var html2 = "<b>" + date + "</b> <br/>" + timeend + "</b> <br/>" + "End Point";
var content2 = "<b>" + "User: " + type + "</b> <br/>" + date + "</b> <br/>" + "User Route";
var encoded_path = google.maps.geometry.encoding.encodePath(points);
console.log(encoded_path);
}
var decoded_path = google.maps.geometry.encoding.decodePath(encoded_path);
// Polyline
var polyOptions = {
path: decoded_path,
map: map,
clickable: true,
strokeColor: "#FF0000",
strokeOpacity: 1.0,
strokeWeight: 2
}
//line text
var info = decoded_path;
// Polyline
var polyline = new google.maps.Polyline(polyOptions);
polyline.setMap(map);
createInfoWindow(polyline, map, infoWindow, content2);
This is the Newer Code:
var map = new google.maps.Map(document.getElementById('map'), myOptions);
var infoWindow = new google.maps.InfoWindow();
// Change this depending on the name of your PHP file
downloadUrl("output-xml.php", function(data) {
var markerbgn=[];
var markerend=[];
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
var routeNum = [];
var mPoints =[];
for (var i = 0; i < markers.length-1; i++) {
var date = markers[i].getAttribute("date").split("-").join("");
var dateAdv = markers[i+1].getAttribute("date").split("-").join("");
var datePrv = [];
var dateEnd = markers[markers.length-1].getAttribute("date").split("-").join("");
var time = markers[i].getAttribute("time");
var timebgn = markers[0].getAttribute("time");
var timeend = markers[markers.length-1].getAttribute("time");
var type = markers[i].getAttribute("usid");
var routesCng=[];
var points=[];
if (dateAdv != date){
if (!routesCng) routesCng=[];
routesCng = i;
routeNum++;
for (var k = 0; k < markers.length; k++) {
points.push(new google.maps.LatLng(
parseFloat(markers[k].getAttribute("lat")),
parseFloat(markers[k].getAttribute("lng"))));
}
setPoints();
setPolyline();
}
//alert([datePrv,time,dateAdv]); //**********************************
var html1 = "<b>" + date + "</b> <br/>" + timebgn + "</b> <br/>" + "Start Point";
var html2 = "<b>" + date + "</b> <br/>" + timeend + "</b> <br/>" + "End Point";
var content2 = "<b>" + type + "</b> <br/>" + dateAdv + "</b> <br/>" + "User Route";
}
function setPoints() {
mPoints = points.splice([routesCng]);
//alert([date,routesCng,dateAdv,routeNum]);
}
function setPolyline() {
alert([date,routesCng,dateAdv,routeNum,mPoints]);
var encoded_path = google.maps.geometry.encoding.encodePath(mPoints);
console.log(encoded_path);
var decoded_path = google.maps.geometry.encoding.decodePath(encoded_path);
var polyOptions = {
path: decoded_path,
map: map,
clickable: true,
strokeColor: "#FF0000",
strokeOpacity: 1.0,
strokeWeight: 2
}
// Polyline
var polyline = new google.maps.Polyline(polyOptions);
//line text
var info = decoded_path;
polyline.setMap(map);
createInfoWindow(polyline, map, infoWindow, content2);
if(decoded_path.length!=0){
markerbgn = new google.maps.Marker({
map: map,
position: decoded_path[0],
draggable: false,
visible: true
});
markerend = new google.maps.Marker({
map: map,
position: decoded_path[decoded_path.length-1],
draggable: false,
visible: true
});
bindInfoWindow(markerbgn, map, infoWindow, html1);
bindInfoWindow(markerend, map, infoWindow, html2);
}
}
});
any help would be greatly appreciated!
I'm not sure why you want to do this in the client, but one way to do it would be to create an array of points for each date:
if (!points[date]) points[date] = [];
points[date].push(new google.maps.LatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng"))));
then create your unique polylines from each of those arrays.
I have been trying to make a Google map which would show multiple markers on different locations. This map is connected to a database where it stores the latitude and longitude. I want to make this map so that I can change the latitude and longitude in the database so that the markers can update and relocate to the new location. But I do not want the whole map to reload, just the data. Here is the code, and thank you for your help!
<script type="text/javascript">
//<![CDATA[
var iconBlue = new GIcon();
iconBlue.image = 'mm_20_blue.png';
iconBlue.shadow = 'mm_20_shadow.png';
iconBlue.iconSize = new GSize(16, 25);
iconBlue.shadowSize = new GSize(27.5, 25);
iconBlue.iconAnchor = new GPoint(7.5, 25);
iconBlue.infoWindowAnchor = new GPoint(5, 1);
var iconRed = new GIcon();
iconRed.image = 'mm_20_red.png';
iconRed.shadow = 'mm_20_shadow.png';
iconRed.iconSize = new GSize(16, 25);
iconRed.shadowSize = new GSize(27.5, 25);
iconRed.iconAnchor = new GPoint(7.5, 25);
iconRed.infoWindowAnchor = new GPoint(5, 1);
var customIcons = [];
customIcons["1"] = iconBlue;
customIcons["2"] = iconRed;
function load() {
if (GBrowserIsCompatible()) {
var map = new GMap2(document.getElementById("map"));
map.setUIToDefault();
map.addControl(new GMapTypeControl());
map.setCenter(new GLatLng(34.081187, -83.980721), 8);
geocoder = new GClientGeocoder();
GDownloadUrl("genxml2.php", function(data) {
var xml = GXml.parse(data);
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var Names = markers[i].getAttribute("Names");
var phoneNum = markers[i].getAttribute("phoneNum");
var gender = markers[i].getAttribute("gender");
var homeAd = markers[i].getAttribute("homeAd");
var lat = markers[i].getAttribute("latitudeE6")
var lng = markers[i].getAttribute("longitudeE6")
var point = new GLatLng(parseFloat(markers[i].getAttribute("latitudeE6")),
parseFloat(markers[i].getAttribute("longitudeE6")));
var marker = createMarker(point, Names, phoneNum, gender, homeAd, lat, lng);
map.addOverlay(marker);
}
}
);
}
}
function createMarker(point, Names, phoneNum, gender, homeAd, lat, lng) {
var marker = new GMarker(point, customIcons[gender]);
place = marker
var html = "<b>Name: " + Names + "</b> <br/>Phone #: " + phoneNum + "</b> <br/>Home Address: " + homeAd + "</b> <br/>Current Address: " + place.address
+ "</b> <br/>Latitude: " + lat + "</b> <br/>Longitude: " + lng;
GEvent.addListener(marker, 'click', function() {
marker.openInfoWindowHtml(html);
});
return marker;
};
//]]>
(some part of the code was excluded, like the MD5 key)
first make function called load_marker
put your code which starting gdownloadurl in new function and load markers when your data change by calling this javascript function. you may need to clear all markers first.
also you may want to reload markers in map event. there are two usefull events you can use.
drag_end and zoom_changed . you can register these by gmap.registerEvent function
edit: added code sample / your code should be like this.
function load() {
if (GBrowserIsCompatible()) {
var map = new GMap2(document.getElementById("map"));
map.setUIToDefault();
map.addControl(new GMapTypeControl());
map.setCenter(new GLatLng(34.081187, -83.980721), 8);
geocoder = new GClientGeocoder();
}
function load_markers() {
/*clear all*/
map.clearOverlays();
GDownloadUrl("genxml2.php", function(data) {
var xml = GXml.parse(data);
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var Names = markers[i].getAttribute("Names");
var phoneNum = markers[i].getAttribute("phoneNum");
var gender = markers[i].getAttribute("gender");
var homeAd = markers[i].getAttribute("homeAd");
var lat = markers[i].getAttribute("latitudeE6")
var lng = markers[i].getAttribute("longitudeE6")
var point = new GLatLng(parseFloat(markers[i].getAttribute("latitudeE6")),
parseFloat(markers[i].getAttribute("longitudeE6")));
var marker = createMarker(point, Names, phoneNum, gender, homeAd, lat, lng);
map.addOverlay(marker);
}
}
);
}
}
You should switch to Google Maps API v3, where pointers are linked to the map and not the opposite. Plus you'll get a bunch of interesting new features for free!