Forum Moderators: open

Message Too Old, No Replies

Trigger Google map event from another page

         

SilverLining

2:47 pm on Mar 22, 2011 (gmt 0)

10+ Year Member



We are using Mike Williams' EGeoXml with the sidebar links, which plots points on a Google Map, depending on data contained in an XML file. What I'm trying to achieve is to access these links from another page.

Here is an example of the href code:

<a name="link_5" href="javascript:myclick(5)">This Place</a>


Here is an example of the sidebar
function makeSidebar() {
var html = "";
for (var i=0; i<gmarkers.length; i++) {
if (!gmarkers[i].isHidden()) {
html += '<a href="javascript:myclick(' + i + ')" name="link_' + i + '" >' + gmarkers[i].myname + '<\/a><br>';
}
}
document.getElementById("side_bar").innerHTML = html;
}


How could one trigger the event from an external page (the link should go to a page with a google map on our site, rather than map.google.com) ?

Thanks

SilverLining

2:24 am on Mar 28, 2011 (gmt 0)

10+ Year Member



I have made some progress. Query string parameters can now be set, but the checkboxes (not mentioned before) no longer update the map display, depending on categories set in XML.

Currently linking to a maker works by appending the url with
?marker=n"
. I have added labels in the XML file and ideally want these labels to be used in the url e.g.
?marker=marker1
, but have not been able to get this working.

gicons
previously set are not displaying and so default Google pins are being used.

Not sure whether the following code is placed within the correct brackets:
show("cat1");
show("cat2");


Lastly, I noticed that the map pins do not display in Chrome and Opera. The page validates with a Transitional DTD in W3C validator.

Do you have any insight into mistakes I have made in the attached code?

To test, please update "unique_key" below, with your Google Map key and save XML as test.xml.

HTML

<!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"/>
<title>Google Maps</title>
<script src="http://maps.google.com/maps?file=api&amp;v=2&amp;sensor=false&amp;key=unique_key" type="text/javascript"></script>
</head>
<body onunload="GUnload()">

<table cellpadding="0" cellspacing="0" border="0" width="50%">
<tr>
<td valign="top">
<form action="#">
<b>Click a checkbox</b><br /><br />
<div style="background: url(cat1.jpg);">Cat1
<input type="checkbox" id="cat1box" onclick="boxclick(this,'cat1')" style="margin-top: 10px;" />
</div>
<div style="background: url(cat2.jpg);">Cat2
<input type="checkbox" id="cat2box" onclick="boxclick(this,'cat2')" style="margin-top: 10px;" />
</div>
</form>
<br />
<div id="map" style="width: 100%; height: 450px; border: 1px solid #000;"></div>
</td>
</tr>
</table>

<!--div id="link"></div-->

<noscript><b>JavaScript must be enabled in order for you to use Google Maps.</b>
However, it seems JavaScript is either disabled or not supported by your browser.
To view Google Maps, enable JavaScript by changing your browser options, and then
try again.
</noscript>

<script type="text/javascript">
//<![CDATA[

if (GBrowserIsCompatible()) {

// ========== Read paramaters that have been passed in ==========

// Before we go looking for the passed parameters, set some defaults
// in case there are no parameters
var id;
var index = -1;

// If there are any parameters at eh end of the URL, they will be in location.search
// looking something like "?marker=3"

// skip the first character, we are not interested in the "?"
var query = location.search.substring(1);

// split the rest at each "&" character to give a list of "argname=value" pairs
var pairs = query.split("&");
for (var i=0; i<pairs.length; i++) {
// break each pair at the first "=" to obtain the argname and value
var pos = pairs[i].indexOf("=");
var argname = pairs[i].substring(0,pos).toLowerCase();
var value = pairs[i].substring(pos+1).toLowerCase();

// process each possible argname - use unescape() if theres any chance of spaces
if (argname == "id") {id = unescape(value);}
if (argname == "marker") {index = parseFloat(value);}
}

var gmarkers = [];
var idmarkers = [];
var gicons = [];

var baseIcon = new GIcon(G_DEFAULT_ICON);
baseIcon.iconAnchor = new GPoint(7,27);
baseIcon.iconSize = new GSize(15,27);
baseIcon.infoWindowAnchor = new GPoint(7,2);
//baseIcon.shadow = "http://chart.apis.google.com/chart?chst=d_map_pin_shadow";
baseIcon.shadowSize = new GSize(22,27);

gicons["cat1"] = new GIcon(baseIcon,"cat1_marker.png");
gicons["cat2"] = new GIcon(baseIcon,"cat2_marker.png");

// A function to create the marker and set up the event window
function createMarker(point,id,html,category) {
var marker = new GMarker(point,gicons[category]);
// === Store the category and name info as a marker properties ===
marker.mycategory = category;
marker.myname = name;
GEvent.addListener(marker, "click", function() {
marker.openInfoWindowHtml(html);
});
// save the info we need to find this marker
gmarkers.push(marker);
idmarkers[id.toLowerCase()] = marker;
return marker;
}

// == shows all markers of a particular category, and ensures the checkbox is checked ==
function show(category) {
for (var i=0; i<gmarkers.length; i++) {
if (gmarkers[i].mycategory == category) {
gmarkers[i].show();
}
}
// == check the checkbox ==
document.getElementById(category+"box").checked = true;
}

// == hides all markers of a particular category, and ensures the checkbox is cleared ==
function hide(category) {
for (var i=0; i<gmarkers.length; i++) {
if (gmarkers[i].mycategory == category) {
gmarkers[i].hide();
}
}
// == clear the checkbox ==
document.getElementById(category+"box").checked = false;
// == close the info window, in case its open on a marker that we just hid
map.closeInfoWindow();
}

// == a checkbox has been clicked ==
function boxclick(box,category) {
if (box.checked) {
show(category);
} else {
hide(category);
}
// == rebuild the side bar
//makeSidebar();
}

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

// == Create the map ==
var map = new GMap2(document.getElementById("map"));
map.addControl(new GLargeMapControl());
map.addControl(new GMapTypeControl());
map.setCenter(new GLatLng(-32.48333,24.06667), 6);

// Read the data from example.xml
var request = GXmlHttp.create();
request.open("GET", "test.xml", true);
request.onreadystatechange = function() {
if (request.readyState == 4) {
var xmlDoc = GXml.parse(request.responseText);
// obtain the array of markers and loop through it
var markers = xmlDoc.documentElement.getElementsByTagName("marker");

for (var i = 0; i < markers.length; i++) {
// obtain the attribues of each marker
var lat = parseFloat(markers[i].getAttribute("lat"));
var lng = parseFloat(markers[i].getAttribute("lng"));
var point = new GLatLng(lat,lng);
var address = markers[i].getAttribute("address");
//var html = markers[i].getAttribute("html");
var name = markers[i].getAttribute("name");
var html = "<b>"+name+"<\/b><p>"+address;
var label = markers[i].getAttribute("label");
// create the marker
var marker = createMarker(point,label,html);
map.addOverlay(marker);
}
// ========= If a parameter was passed, open the info window ==========
if (id) {
if (idmarkers[id]) {
GEvent.trigger(idmarkers[id],"click");
} else {
alert("id "+id+" does not match any marker");
}
}
if (index > -1) {
if (index < gmarkers.length) {
GEvent.trigger(gmarkers[index],"click");
} else {
alert("marker "+index+" does not exist");
}
}

}

}

// == show or hide the categories initially ==
show("cat1");
show("cat2");

request.send(null);
}

// display a warning if the browser was not compatible
else {
alert("Sorry, the Google Maps API is not compatible with this browser");
}

//]]>
</script>
</body>

</html>


XML: test.xml
<markers>
<marker name="Marker 1" address="Marker 1 html" lat="-33.3077564591906" lng="26.53123140335083" category="cat2" label="marker1" />
<marker name="Marker 2" address="Marker 2 html" lat="-32.87892" lng="27.389174" category="cat2" label="marker2" />
<marker name="Marker 3" address="Marker 3 html" lat="-33.95062247304173" lng="25.571258068084717" category="cat1" label="marker3" />
<marker name="Marker 4" address="Marker 4 html" lat="-31.897872259602124" lng="26.871893405914307" category="cat1" label="marker4" />
</markers>

astupidname

10:51 am on Mar 28, 2011 (gmt 0)

10+ Year Member



In the createMarker function you have:
marker.mycategory = category;

but you are not obtaining from the xml and passing the category to the createMarker function.
Also in createMarker you have:
marker.myname = name;

but there is no 'name' variable, so for each marker you have created, it's mycategory is undefined and it's myname is "" (at least "" is what it shows up in firebug as, should actually be null I believe... Oh wait the window object actually has a name property which by default is "" and which may be defined, so you are actually accessing that property of the window by mistake).

The revised script (which I strongly recommend moving to an external file) with the above corrections and some minor rearranging and formatting:

// A function to create the marker and set up the event window
function createMarker(point, id, html, category) {
var marker = new GMarker(point, gicons[category]);
// === Store the category and name info as a marker properties ===
marker.mycategory = category;
marker.myname = id;
GEvent.addListener(marker, "click", function() {
marker.openInfoWindowHtml(html);
});
// save the info we need to find this marker
gmarkers.push(marker);
idmarkers[id.toLowerCase()] = marker;
return marker;
}

// == shows all markers of a particular category, and ensures the checkbox is checked ==
function show(category) {
for (var i=0; i < gmarkers.length; i++) {
if (gmarkers[i].mycategory == category) {
gmarkers[i].show();
}
}
// == check the checkbox ==
document.getElementById(category+"box").checked = true;
}

// == hides all markers of a particular category, and ensures the checkbox is cleared ==
function hide(category) {
for (var i=0; i < gmarkers.length; i++) {
if (gmarkers[i].mycategory == category) {
gmarkers[i].hide();
}
}
// == clear the checkbox ==
document.getElementById(category+"box").checked = false;
// == close the info window, in case its open on a marker that we just hid
map.closeInfoWindow();
}

// == a checkbox has been clicked ==
function boxclick(box,category) {
if (box.checked) {
show(category);
} else {
hide(category);
}
// == rebuild the side bar
//makeSidebar();
}

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

if (GBrowserIsCompatible()) {
// ========== Read paramaters that have been passed in ==========
// Before we go looking for the passed parameters, set some defaults
// in case there are no parameters
var id;
var index = -1;
// If there are any parameters at eh end of the URL, they will be in location.search
// looking something like "?marker=3"
// skip the first character, we are not interested in the "?"
var query = location.search.substring(1);
// split the rest at each "&" character to give a list of "argname=value" pairs
var pairs = query.split("&");
for (var i=0; i < pairs.length; i++) {
// break each pair at the first "=" to obtain the argname and value
var pos = pairs[i].indexOf("=");
var argname = pairs[i].substring(0,pos).toLowerCase();
var value = pairs[i].substring(pos+1).toLowerCase();
// process each possible argname - use unescape() if theres any chance of spaces
if (argname == "id") {
id = unescape(value);
} else if (argname == "marker") {
index = parseFloat(value);
}
}
var gmarkers = [];
var idmarkers = [];
var gicons = [];
var baseIcon = new GIcon(G_DEFAULT_ICON);
baseIcon.iconAnchor = new GPoint(7,27);
baseIcon.iconSize = new GSize(15,27);
baseIcon.infoWindowAnchor = new GPoint(7,2);
//baseIcon.shadow = "http://chart.apis.google.com/chart?chst=d_map_pin_shadow";
baseIcon.shadowSize = new GSize(22,27);
gicons["cat1"] = new GIcon(baseIcon,"cat1_marker.png");
gicons["cat2"] = new GIcon(baseIcon,"cat2_marker.png");
// == Create the map ==
var map = new GMap2(document.getElementById("map"));
map.addControl(new GLargeMapControl());
map.addControl(new GMapTypeControl());
map.setCenter(new GLatLng(-32.48333,24.06667), 6);
// Read the data from example.xml
var request = GXmlHttp.create();
request.open("GET", "test.xml", true);
request.onreadystatechange = function() {
if (request.readyState == 4) {
var xmlDoc = GXml.parse(request.responseText);
// obtain the array of markers and loop through it
var markers = xmlDoc.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
// obtain the attribues of each marker
var lat = parseFloat(markers[i].getAttribute("lat"));
var lng = parseFloat(markers[i].getAttribute("lng"));
var point = new GLatLng(lat,lng);
var address = markers[i].getAttribute("address");
//var html = markers[i].getAttribute("html");
var name = markers[i].getAttribute("name");
var html = "<b>"+name+"<\/b><p>"+address;
var label = markers[i].getAttribute("label");
var category = markers[i].getAttribute('category');
// create the marker
var marker = createMarker(point, label, html, category);
map.addOverlay(marker);
}
// ========= If a parameter was passed, open the info window ==========
if (id) {
if (idmarkers[id]) {
GEvent.trigger(idmarkers[id],"click");
} else {
alert("id "+id+" does not match any marker");
}
}
if (index > -1) {
if (index < gmarkers.length) {
GEvent.trigger(gmarkers[index],"click");
} else {
alert("marker "+index+" does not exist");
}
}
}
};
// == show or hide the categories initially ==
show("cat1");
show("cat2");
request.send(null);
} else {// display a warning if the browser was not compatible
alert("Sorry, the Google Maps API is not compatible with this browser");
}

If anybody's wondering, how to post formatted code on webmasterworld [webmasterworld.com]
Do not copy formatted code on webmasterworld from IE, use other browser such as Firefox.


Also, test.xml should start with an opening xml prologue such as:
<?xml version="1.0" encoding="iso-8859-1"?>

astupidname

11:24 am on Mar 28, 2011 (gmt 0)

10+ Year Member



Oh, and as for the icons, check to make sure your icons are actually there (paths correct and all), I was actually testing with my own:
  var iconUrlBase = '../../Maps/images/maps_google_com markers/';
//gicons["cat1"] = new GIcon(baseIcon,"cat1_marker.png");
//gicons["cat2"] = new GIcon(baseIcon,"cat2_marker.png");
gicons["cat1"] = new GIcon(baseIcon, iconUrlBase + "firedept.png");
gicons["cat2"] = new GIcon(baseIcon, iconUrlBase + "hospitals.png");


and worked for me in FF, IE & Chrome. (No Opera available to check)

SilverLining

1:30 pm on Mar 28, 2011 (gmt 0)

10+ Year Member



Thanks so much, it's working now. The icons were present, so not sure why they were not working.

Once last question: It still does not work if I add the label to the url e.g.
?marker=marker1
, only
?marker=0
,
?marker=1
etc. works. Any ideas?

Thanks so much re the link for formatting code. I was actually wondering about that.

SilverLining

2:52 pm on Apr 5, 2011 (gmt 0)

10+ Year Member



What are the implications of upgrading to Google Maps v 3.2? I have updated the script to:

<script src="http://maps.google.com/maps?file=api&v=3.2&amp;sensor=false&amp;key=unique_key" type="text/javascript"></script>


Viewing the map inside the CMS behaves funny (map leaves grey blocks and does not load fully), however on a local test page it seems fine. I can't see where the conflict is coming from.