Google Map Custom Marker Dependent on Field Value - google-maps-api-3

I am using the code below to populate a Google Map with markers for all the lat and lng values I hold in a MySQL database.
What I would like to do, if at all possible, is to extend this a little more and have the ability to show different coloured markers dependent on a field value, to be more specific, if the value in the field 'finds' is zero then it will be one colour, but if it has a value of one or greater for it to be another colour.
I've found how to do this if the field value is a text value but not numeric. I've tried to change my code, to how (from a beginners perspective) I thought it might be be, but I can't get this to work.
<!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" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>All Locations</title>
<link rel="stylesheet" href="css/style.css" type="text/css" media="all" />
<script type="text/javascript"
src="http://maps.google.com/maps/api/js?sensor=false&language=en"></script>
<script type="text/javascript">
var customIcons = {
if 'finds'.value=0: {
icon: 'http://labs.google.com/ridefinder/images/mm_20_blue.png',
shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
},
else {
icon: 'http://labs.google.com/ridefinder/images/mm_20_red.png',
shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
}
};
function load() {
var map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(54.312195845815246,-4.45948481875007),
zoom:6,
mapTypeId: 'roadmap'
});
// Change this depending on the name of your PHP file
downloadUrl("phphfile.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("locationname");
var address = markers[i].getAttribute("address");
var findsvalue = markers[i].getAttribute("finds");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("osgb36lat")),
parseFloat(markers[i].getAttribute("osgb36lon")));
var marker = new google.maps.Marker({
map: map,
position: point,
icon: icon.icon,
shadow: icon.shadow
});
}
});
}
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"></div>
</body>
</html>

This was a lot simpler than I thought.
It was just a case of replacing the text with the numeric value.
Chris

Related

Centering Google Maps from a marker

Im triying to create a map with a marker from a position taken from a database. I succeed creating the map using this tutorial. The problem is that i have to enter manually the center position when i create the map.
¿Is there a way to center the map using the marker?. The code that im using is the following:
<!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("loadposition.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("Latitud")),
parseFloat(markers[i].getAttribute("Longitud")));
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>
Also my XML generated file looks like this:
<markers>
<marker Latitud="-33.449148" Longitud="-70.552886"/>
</markers>
Thanks a lot!
I used this in an app after adding the marker. Might help you.
bounds = new google.maps.LatLngBounds();
bounds.extend(marker.position);
if (!bounds.isEmpty())
map.panTo(bounds.getCenter());
Original idea was to find the center of a bunch of markers, so this might be overkill.

How can I get my external links to trigger click events on cooresponding google map markers?

Im trying to figure out how I can have the links that appear in the external div trigger click events on the corresponding map marker (opening the info window). I think my code is solid (except maybe where I tried copying the array of location data to get the click function to be able to access the array given the scope hurdles i ran into - Im just not sure what to do to get it to work right. Can anyone shed any light on what I need to modify in my code? Thanks.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<title>Untitled Document</title>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false" type="text/javascript"></script>
<script type="text/javascript" src="http://google-maps-utility-library-v3.googlecode.com/svn/trunk/infobox/src/infobox.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<script type="text/javascript">
var gmarkers = [];
function initialize() {
var locations = [
['DESCRIPTION', 41.926979, 12.517385, 3],
['DESCRIPTION', 41.914873, 12.506486, 2],
['DESCRIPTION', 61.918574, 12.507201, 1]
];
window.map = new google.maps.Map(document.getElementById('map'), {
panControl: false,
zoomControl: false,
scaleControl: false,
streetViewControl: false,
mapTypeControl: false,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow();
var bounds = new google.maps.LatLngBounds();
// CREATE THE MARKERS ON THE MAP FROM THE ARRAY DATA
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map
});
gmarkers.push(marker);
bounds.extend(marker.position);
// ADD A LINK FOR THIS MARKER TO THE DIV, WHEN CLICKED, IT SHOULD TRIGGER THE MARKER CLICK / INFO WINDOW FOR COORESPONDING MARKER
$('#listdiv').append('<p>' + locations[i][0] + '');
google.maps.event.addListener(marker, 'click', (function (marker, i) {
return function () {
infowindow.setContent(locations[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
}
map.fitBounds(bounds);
var listener = google.maps.event.addListener(map, "idle", function () {
//map.setZoom(10); // NO LONGER NEED, SINCE FITBOUNDS SCALES VIEW TO SHOW ALL MARKERS?
google.maps.event.removeListener(listener);
});
}
// THIS FUNCTION IS SUPPOSED TO BE CALLED ON THE EXTERNAL LINK CLICKS - SHOULD OPEN THE COORESPONDING MARKER/INFO WINDOW.
function show(i) {
google.maps.event.trigger(gmarkers[i], 'click');
alert("I see a click.");
}
</script>
</head>
<body onload="initialize();" marginheight="0" marginwidth="0" topmargin="0" leftmargin="0">
<div id="map" style="width: 100%; height: 300px;"></div>
<div id="listdiv" style="width:100%; border: 2px solid blue; color: black; font-family: Arial, Helvetica, sans-serif; font-size:14px;"></div>
</body>
</html>
Remove this line:
gmarkers = locations.concat();
add this line after you create the marker:
gmarkers.push(marker);

Marker do not appear when I try to integrate Google Maps into an existing web page

I previously prepare a javascript that shows some marker downloaded in JSON format, from a webservice.
The code is:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>MAP</title>
<link type="text/css" href="css/style.css" rel="stylesheet" media="all" />
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false&v=3.8"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript" src="map_bar.js"></script>
</head>
<body>
<h1>MAPPA</h1>
<div id="map"></div>
</body>
</html>
that calls the map_bar.js:
(function() {
window.onload = function() {
// Creating a new map
var map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(80.650535,41.886146),
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
// Creating a global infoWindow object that will be reused by all markers
function createPoints(json){
var infoWindow = new google.maps.InfoWindow();
// Looping through the JSON data
for (var i = 0, length = json.locations.length; i < length; i++) {
var data = json.locations[i],
latLng = new google.maps.LatLng(data.lat, data.long);
console.log(data.long);
var iconBase = 'https://maps.google.com/mapfiles/kml/shapes/';
var marker = new google.maps.Marker({
position: latLng,
map: map,
title: data.nombre,
icon: 'beer.png'
});
(function(marker, data) {
// Attaching a click event to the current marker
google.maps.event.addListener(marker, "click", function() {
info = data.nombre+'<br/>'+data.offerta+'<br/>'+data.horario;
infoWindow.setContent(info); //esto escibe las info
infoWindow.open(map, marker);
});
})
(marker, data);
}
}
// Get the JSON data from PHP script
var json ;
$.getJSON("http://mywebservice.php").done(function(data) {
console.log(data);
json = data;
createPoints(json);
});
}
})();
It works, but the problem appears when I trying to integrate that in an existing webpage.
I have some sections and putting the same code in my "map section", the map appears but not markers.
The console.log(data) into the getJSON method not give back the point. It strange because the same code works in a "stand alone" page.
Any idea about that?
Thanks in advance.
jquery getJSON is subject to the same origin policy, a sub-domain is not the same domain as the main domain.
Using a relative reference to a file in the sub-domain fixes the issue.

google maps loading map on button click - loading markers with another button

I'm trying to load markers on the click of a button, but somewhere i'm missing something. 1. map pulls out and loads with one button click. 2. markers load with the click of a different button. here's what i have:
<!DOCTYPE>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title></title>
<link rel="stylesheet" type="text/css" href="
<?php
$stylesarray = array("field");
echo $stylesarray[mt_rand(0,count($stylesarray)-1)];
?>.css">
<link rel="shortcut icon" href="images/favicon.ico">
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="http://maps.googleapis.com/maps/api/js?key=xxx&sensor=false"></script>
<script type="text/javascript">
var map = null;
$(document).ready(function(){
var lat=document.getElementById("latitude");
var long=document.getElementById("longitude");
if (navigator.geolocation){
navigator.geolocation.getCurrentPosition(showPosition);
}
function showPosition(position) {
lat.value=+position.coords.latitude;
long.value=+position.coords.longitude;
}
});
function load() {
var map = new google.maps.Map(document.getElementById("mapcontainer"), {
center: new google.maps.LatLng(20,0),
zoom: 3,
styles: mapstyle,
mapTypeControl: false,
navigationControl: false,
streetViewControl: false,
maxZoom: 8,
minZoom: 3,
mapTypeId: 'roadmap'
});
}
function getmarkers(){
downloadUrl("markers.php", function(data) {
//alert ("it works");
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var id = markers[i].getAttribute("id");
var info = markers[i].getAttribute("info");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("latitude")),
parseFloat(markers[i].getAttribute("longitude")));
var date = markers[i].getAttribute("date");
var html = "<div id='tooltip'><div id='tiptext'>" + info
+ "<div id='number'>" + id + "</div>"
+ "<div id='date'>" + date + "</div>"
+ "</div></div>";
var marker = new google.maps.Marker({
map: map,
position: point,
icon: 'images/mapicon.png'
});
createTooltip(marker, html);
}
});
</script>
</head>
<body>
<div id="mapcontainer">
<form>
<input type="button" id="map" onClick="load()"></input>
</form>
<form>
<input type="button" onClick="getmarkers()"></input>
</form>
</body>
</html>
xml sample:
<markers>
<marker id="330" info="blahblah" date="2012-10-03" latitude="20.00" longitude="-81.00"/>
</markers>
Your map variable is local to your initialize function. It won't be accessible to the code that loads the markers.
Try defining it globally (outside of any functions):
var map = null;
Then initialize it in your load function
function load() {
map = new google.maps.Map(document.getElementById("mapcontainer"), {
The problem (after syntax errors) with your posted code is that the getmarkers function is local to the load function. It needs to be global to be called by an HTML element click function.
Live working version based off your example code
It seems like you do not declare the map variable in the global scope. Only in the load function scope, declare it as a global variable and it should work.
var map = null; // Declaring map in the global scope
function load() {
// map references to global scope
map = new google.maps.Map(document.getElementById("mapcontainer"), {
...
}
downloadUrl("markerinfo.php", function(data) {
...
var marker = new google.maps.Marker({
map: map, // map references to global scope
position: point,
icon: 'images/mapicon.png'
});
createTooltip(marker, html);
}
});
Try wrapping the DownloadUrl function call in another function and call that instead.
<input type="button" id="markerload" onClick="getMarkers()"></input>
function getMarkers() {
downloadUrl("markerinfo.php", function(data) {
...
});
}
function getmarkers() is designed to retrieve all markers with a for loop
for (var i = 0; i < markers.length; i++) {
To load one marker at a time you will need to increment it for each button click
Ie Var i =0 globally
Increment i at end of getmarkers() i++
You should stop the increments after the last member of array when it gets to markers.length

update markers without reloading the web page google maps v3

First of all I apologize for my poor English but I can not find the answer to my question on all French forums.
I am developing an application that is to make real-time tracking of a fleet of vehicles.
I'm at the end of this application but I have a problem. I can not update my markers without reloading my web page.
I tried with settimeout() but it still charging my map
here is my code thank you for your help.
ps: when completed this application will be available in open source
<html lang="fr">
<head>
<link rel="stylesheet" media="screen" type="text/css" title="Exemple" href="theme.css"/>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<meta charset="UTF-8" />
<title>Geonano V1</title>
<style type="text/css">
html{height: 100%}
body{height: 100%; margin: 0px; padding: 0px}
#EmplacementDeMaCarte{height: 100%}
</style>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
function initialisation() {
var tableauLieux = [
//here I have a loop in php to get my markers in my database
["Paris", 48.86110, 2.34459],
["Versailles", 48.78199, 2.11045]
];
var optionsCarte = {
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var maCarte = new google.maps.Map(document.getElementById("EmplacementDeMaCarte"), optionsCarte);
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < tableauLieux.length; i++) {
var Lieu = tableauLieux[i];
var pointLieu = new google.maps.LatLng(Lieu[1], Lieu[2]);
bounds.extend(pointLieu);
var marqueurLieu = new google.maps.Marker({
position: pointLieu,
map: maCarte,
title: Lieu[0],
icon : Lieu[3],
clickable: true
});
//création de l'info-bulle
var infoBulle = new google.maps.InfoWindow({
content: Lieu[0]//ici on peut mettre des balises HTML
});
google.maps.event.addListener(marqueurLieu, 'click', function() {
infowindow.setContent(Lieu[i][0]);
infoBulle .open(maCarte,marqueurLieu);
});
}
maCarte.fitBounds(bounds);
}
google.maps.event.addDomListener(window, 'load', initialisation);
setInterval("initialisation()", 5000);
</script>
</head>
<body>
<div id="EmplacementDeMaCarte"></div>
</body>
<META HTTP-EQUIV="Refresh" CONTENT="120; URL=http://localhost/geonano.php">
</html>
You'll have to request a ressource(may be a PHP-script) which returns the data for the markers(tableauLieux) using AJAX.
Once you got the response, remove the current markers and create the new markers.
If I understand it correctly, you're redrawing the map each 5 second with all the markers.
Bascily what you want to do is store your marker in an array that you can loop through at a later time to change their lat and lng. Clear them from the map, change the information and then put them back on the map. Changing the information is going to need some ajax.
marker.setMap(null);
a good way to do that is using something like
refreshIntervalId = setInterval("requestPoints()", 4000);
function requestPoints() {
$.ajax({
url:'{% url 'gpstracking.ajax.request_tracks' %}',
type: 'get',
dataType: 'json',
data: {
vehicles: vehicles
},
success: function (positions) {
updatePoints (positions);
}
});
}
function updatePoints (positions) {
console.debug('updating markers');
var lttd;
var lgtd;
for (var i=0; i < positions.length; i++) {
lttd = positions[i].latitude;
lgtd = positions[i].longitude;
position = map.createPosition({
lat: lttd,
lng: lgtd,
});
markers[positions[i].registration].setPosition(position);
};
if (positions.length > 1) {
//map.fitZoom();
} else {
map.setCenter (lttd, lgtd);
}
}

Resources