'myFunction is not a function', JS & Google Maps v 3? - javascript

Hello I cannot figure out why I get this error.
I've got a list with inputs which values contain lat/long/name/address.
Printing the markers on the map works fine, using the infowin workED fine, till I realized that it only openend the same info in all windows. Soo, obviously I needed to attach this (the marker i just clicked) to the eventListner.
But, when doing this I get an error saying view.createMarkerHTML is not a function.
Question: What do I do to attach the right info to be open, on the right marker?
view = {
map: {
init: function init (){
view.map.initMap();
},
initMap: function initMap() {
if(navigator.geolocation) {
function hasPosition(position) {
var point = new google.maps.LatLng(position.coords.latitude, position.coords.longitude),
myOptions = {
zoom: 12,
center: point,
mapTypeId: google.maps.MapTypeId.ROADMAP
},
mapDiv = document.getElementById("map"),
map = new google.maps.Map(mapDiv, myOptions);
view.map.handleMarkers(map);
}
navigator.geolocation.getCurrentPosition(hasPosition);
}
},
handleMarkers: function handleMarkers(map) {
var list = $('#pois input'),
l = list.length,
i = 0, lat = '', long = '', marker = {}, theName = '', address = '', info = {};
for (i = 0; i < l; i += 1) {
info = $(list[i]).val().split('|');
lat = parseFloat(info[0], 10);
long = parseFloat(info[1], 10);
theName = info[2];
address = info[3];
marker = new google.maps.Marker({
position: new google.maps.LatLng(lat, long),
map: map,
icon: icon
});
google.maps.event.addListener(marker, 'click', function() {
currentMarker = this;view.map.createMarkerHTML(map, theName, address);
});
}
} ,
createMarkerHTML: function createMarkerHTML(map, theName, address) {
var contentString =
'<div id="gMapInfoWin">' +
'<h1>' + theName + '</h1>' +
'<ul>' +
'<li>' + address + '</li>' +
'</ul>' +
'</div>'
;
currentMarker.infowindow = new google.maps.InfoWindow({
content: contentString
});
currentMarker.infowindow.open(map, currentMarker);
}
}
};

Shouldn't you use a closure to keep the values of your variables set in the loop ?
(function(theName, address) {
google.maps.event.addListener(marker, 'click', function() {
currentMarker = this;view.map.createMarkerHTML(map, theName, address);
});
}(theName, address));
You could even add your marker in parameter instead of using currentMarker

I'll wager that it's a scoping issue. Not having access to your libs I can't be sure that this will work, but try replacing:
google.maps.event.addListener(marker, 'click', function() {
currentMarker = this;view.map.createMarkerHTML(map, theName, address);
});
with this:
google.maps.event.addListener(marker,
'click',
createClickListener( this,
map,
theName,
address ) );
and then add this function somewhere else in the program:
function createClickListener( cm, map, theName, address )
{
return function() {
currentMarker = cm;
view.map.createMarkerHTML(map, theName, address);
}
}

for (i = 0; i < l; i += 1) {
info = $(list[i]).val().split('|');
lat = parseFloat(info[0], 10);
long = parseFloat(info[1], 10);
marker = new google.maps.Marker({
position: new google.maps.LatLng(lat, long),
map: map,
icon: icon
});
marker.theName = info[2];
marker.address = info[3];
google.maps.event.addListener(marker, 'click', function() {
currentMarker = this;
m_name = this.theName;
m_address = this.address
view.map.createMarkerHTML(map, m_name, m_address);
});
}
marker.theName = info[2];
marker.address = info[3];
currentMarker = this;
m_name = this.theName;
m_address = this.address
... is the soulution!

Related

Google Maps can't read property 'extend' of undefined after page load

I'm trying to increase page speed by loading my Google Maps two seconds after page load. While doing so, I keep on getting "Cannot read property 'extend' of undefined". I know there is some asynchronous loading going on but I'm not sure how to get it in proper order to get this map to load 2 seconds after the page is done. Any help is greatly appreciated.
Page Code:
<div id="mapCont"></div>
<script defer type='text/javascript' src='/js/maps.js'></script>
maps.js
$(window).bind("load", function() {
$.getScript('https://maps.googleapis.com/maps/api/js?key=key', function()
{
setTimeout(function(){
function doMap(callback) {
$("#mapCont").html('<div id="mapInfoManual" class="searchMap mb5"></div>');
callback();
}
doMap(function() {
initialize();
var map = null;
var markers = [];
var openedInfoWindow ="";
var bounds = new google.maps.LatLngBounds();
function initialize() {
var mapOptions = {
zoom: 8,
center: new google.maps.LatLng(64.85599578876611, -147.83363628361917),
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: true,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
},
zoomControl: true,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.SMALL
}
};
map = new google.maps.Map(document.getElementById("mapInfoManual"),
mapOptions);
google.maps.event.addListener(map, 'zoom_changed', function() {
zoomChangeBoundsListener = google.maps.event.addListener(map, 'bounds_changed', function(event) {
if (this.getZoom() > 20) // Change max/min zoom here
this.setZoom(18);
google.maps.event.removeListener(zoomChangeBoundsListener);
});
});
addMarker();
}
function addMarker() {
var bounds = new google.maps.LatLngBounds();
for (i = 0; i < markersArray.length; i++) {
CodeAddress(markersArray[i]);
}
}
// Address To Marker
function CodeAddress(markerEntry) {
var mytitle = (markersArray[i]['title']);
var myaddress = (markersArray[i]['address']);
var linkid = (markersArray[i]['linkid']);
var linkurl = (markersArray[i]['linkurl']);
var image = { url: '/images/MapPin.png', };
var lat = markerEntry['lat'];
var long = markerEntry['long'];
// var myLatLng = {lat: markerEntry['lat'], lng: markerEntry['long']};
var myLatlng = new google.maps.LatLng(parseFloat(lat),parseFloat(long));
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
icon: image
});
bounds.extend(marker.getPosition());
var infoWindowContent = "<div class='cityMapInfoPop'><span style='font-weight:700;'>"+ mytitle +"</span><br /><br />" + myaddress + "<br /><br /><a href='/center/" + linkurl + "/'>More Details</a></div>";
openInfoWindow(marker, infoWindowContent);
markers.push(marker);
map.fitBounds(bounds);
}
//Info Window
function openInfoWindow(marker, infoWindowContent) {
var infowindow = new google.maps.InfoWindow({
content: '<div class="cityMapInfoPop">' + infoWindowContent + '</div>'
});
google.maps.event.addListener(marker, 'click', function() {
if (openedInfoWindow != "") {
openedInfoWindow.close();
}
infowindow.open(map, marker);
openedInfoWindow = infowindow;
});
}
});
}, 2000);
});
});
The initial https://maps.googleapis.com/maps/api/js?key=key loads additional scripts that are not being captured by your implementation. The package, https://www.npmjs.com/package/#googlemaps/js-api-loader, enables the following pattern and is probably what you want:
import { Loader } from '#googlemaps/js-api-loader';
const loader = new Loader({
apiKey: "",
version: "weekly",
libraries: ["places"]
});
loader
.load()
.then(() => {
doMap();
initialize();
})
.catch(e => {
// do something
});
Alternative(use callback) if you want JQuery and your existing pattern:
window.callback = () => {
doMap();
initialize();
};
$(window).bind("load", function() {
$.getScript('https://maps.googleapis.com/maps/api/js?key=key&callback=callback', () => {}); // do nothing here
Also related: https://developers.google.com/maps/documentation/javascript/examples/programmatic-load-button

Google Maps API v3 infoWindow.close() not closing others on click

I have been working on this for a while now. I have looked at multiple stack overflow posts on the topic and several tutorials, but I have not been able to get infoWindow.close() to work.
I have even tried using jQuery to click $('#googleMap > div > div > div:nth-child(1) > div:nth-child(4) > div:nth-child(4) > div:nth-child(1) > div:nth-child(3)').click(); which actually seems to work in the browser console, but not when running the click listener.
Any suggestions or directions are much appreciated.
d3.csv('/data/locs.csv', function(locs){
var obj = [];
for(i=0;i<locs.length;i++) {
var country = locs[i].country;
var location = locs[i].location;
var lat = locs[i].lat;
var long = locs[i].long;
var description = locs[i].description;
obj.push({
con: country,
location: location,
lat: lat,
lng: long,
description: description
});
}
console.log(obj);
initMap(obj)
});
function initMap(obj, error) {
if (error){console.log("Error: "+error)}
var openInfoWindow = null;
var mapProp = {
center: {lat: 39.8283, lng: -98.5795},
zoom: 2
};
var map = new google.maps.Map(document.getElementById("googleMap"), mapProp);
var pointLoc = [];
var labels = [];
var descrip = [];
var locale = [];
for(i=0;i<obj.length;i++) {
pointLoc.push({lat: obj[i].lat, lng: obj[i].lng});
labels.push(obj[i].con);
descrip.push(obj[i].description);
locale.push(obj[i].location);
}
map.data.loadGeoJson();
for (var i = 0; i < pointLoc.length; i++) {
var coords = pointLoc[i];
var latLng = new google.maps.LatLng(coords.lat,coords.lng);
var marker = new google.maps.Marker({
position: latLng,
map: map
});
var contentStr = '<div id="popcontent">'+
'<div id="siteNotice">'+
'</div>'+
'<h1 id="firstHeading" class="firstHeading">'+descrip[i]+'</h1>'+
'<p>'+locale[i]+', '+labels[i]+'</p>' +
'</div>';
var infoWindow = new google.maps.InfoWindow({
maxWidth: 300
});
google.maps.event.addListener(marker,'click', (function(marker,contentStr,infowindow){
infowindow.close();
return function() {
infowindow.setContent(contentStr);
infowindow.open(map, marker);
};
})(marker,contentStr,infoWindow));
}
}
Stephen's answer identifies the problem with the infowindow. I want to help you learn to write simpler code.
There is a lot of complication in this code that you don't need; in fact you can get rid of most of the code!
The code first converts the locs array to a very similar obj array that has a couple of fields renamed.
Then it converts this obj array to four individual arrays pointLoc, labels, descrip, and locale.
None of this conversion is needed.
Also, when naming an array, I recommend using a plural name for the array and the singular form of that name for an element of the array. You did this in some places, just not consistently.
There is a map.data.loadGeoJson(); call that doesn't do anything because no URL is provided.
You also don't need the function-that-returns-a-function in the click listener, if you provide a closure in a simpler way as in the code below.
Here's an example of how you could do the whole thing in a much simpler manner:
d3.csv( '/data/locs.csv', function( places ) {
var infoWindow;
var map = new google.maps.Map( document.getElementById('googleMap'), {
center: { lat: 39.8283, lng: -98.5795 },
zoom: 2
});
places.forEach( function( place ) {
var marker = new google.maps.Marker({
position: new google.maps.LatLng( place.lat, place.long ),
map: map
});
google.maps.event.addListener( marker, 'click', function() {
if( infoWindow ) infoWindow.close();
var content =
'<div id="popcontent">' +
'<div id="siteNotice">' +
'</div>' +
'<h1 id="firstHeading" class="firstHeading">' + place.description + '</h1>' +
'<p>' + place.location + ', ' + place.country + '</p>' +
'</div>';
infoWindow = new google.maps.InfoWindow({
maxWidth: 300,
content: content
});
infoWindow.open( map, marker );
});
});
});
Your variable infoWindow goes out of scope when returning a function, and you not modifying the outer infoWindow, but the one passed into the function. Try this.
d3.csv('/data/locs.csv', function(locs){
var obj = [];
for(i=0;i<locs.length;i++) {
var country = locs[i].country;
var location = locs[i].location;
var lat = locs[i].lat;
var long = locs[i].long;
var description = locs[i].description;
obj.push({
con: country,
location: location,
lat: lat,
lng: long,
description: description
});
}
console.log(obj);
initMap(obj)
});
function initMap(obj, error) {
if (error){console.log("Error: "+error)}
var openInfoWindow = null;
var mapProp = {
center: {lat: 39.8283, lng: -98.5795},
zoom: 2
};
var map = new google.maps.Map(document.getElementById("googleMap"), mapProp);
var pointLoc = [];
var labels = [];
var descrip = [];
var locale = [];
for(i=0;i<obj.length;i++) {
pointLoc.push({lat: obj[i].lat, lng: obj[i].lng});
labels.push(obj[i].con);
descrip.push(obj[i].description);
locale.push(obj[i].location);
}
map.data.loadGeoJson();
for (var i = 0; i < pointLoc.length; i++) {
var coords = pointLoc[i];
var latLng = new google.maps.LatLng(coords.lat,coords.lng);
var marker = new google.maps.Marker({
position: latLng,
map: map
});
var contentStr = '<div id="popcontent">'+
'<div id="siteNotice">'+
'</div>'+
'<h1 id="firstHeading" class="firstHeading">'+descrip[i]+'</h1>'+
'<p>'+locale[i]+', '+labels[i]+'</p>' +
'</div>';
var infoWindow = new google.maps.InfoWindow({
maxWidth: 300
});
google.maps.event.addListener(marker,'click', (function(marker,contentStr,infowindow){
infowindow.close();
return((function(infowindow) {
infowindow.setContent(contentStr);
infowindow.open(map, marker);
})(infowindow));
})(marker,contentStr,infoWindow));
}
}
I was able to handle it easily with jQuery trigger event.
jQuery('.gm-ui-hover-effect').trigger('click');
Just put above code inside addListener function of marker and don't forget to include jQuery in your script.

adding infowindow to google maps

I'm trying to add some infowindow content to my markers on a google map. I can query my server, get some data, put the markers on the map. That works. What doesn't work is that nothing happens when I click on the marker. I would think that the infowindow would popup. Unfortunately, it has been so long since I have done google maps programming, I am effectively starting over. For some reason, the marker's click event is not being called. Any suggestions regarding my dumbness are appreciated. TIA
<script>
var map, geocoder;
var Markers = [];
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: { lat: 0.0, lng: 0.0 },
zoom: 12
});
if (!Modernizr.geolocation) {
alert("Your browser sucks. Get a new one, maybe one that is up to date and supports GPS.")
return;
}
else {
navigator.geolocation.getCurrentPosition(show_map);
}
}
function show_map(position) {
map.setZoom(12);
var Latitude = position.coords.latitude;
var Longitude = position.coords.longitude;
map.setCenter({ lat: Latitude, lng: Longitude });
var bounds = map.getBounds();
var url = "/api/xxxxxxxxjsonendpoint";
var lowerLeft = bounds.getSouthWest();
var upperRight = bounds.getNorthEast();
var lat0 = lowerLeft.lat();
var lng0 = lowerLeft.lng();
var lat1 = upperRight.lat();
var lng1 = upperRight.lng();
var geocoder = new google.maps.Geocoder();
var data = { LowerLeftLat: lat0, LowerLeftLng: lng0, UpperRightLat: lat1, UpperRightLng: lng1 };
$.get(url, data, function (result) {
for (var i = 0; i < result.length; i++) {
var address = result[i].Address1 + " " + (result[i].Address2 != null ? result[i].Address2 : "") + " " + result[i].City + " " + result[i].Province + " " + result[i].PostalCode + " " + result[i].Country;
var marker = new google.maps.Marker({
position: geocodeAddress(geocoder, map, address),
map: map,
title: address
});
var infowindow = new google.maps.InfoWindow({
content: i
});
makeInfoWindowEvent(map, infowindow, "test" + i, marker);
}
});
}
function geocodeAddress(geocoder, resultsMap, address) {
geocoder.geocode({ 'address': address }, function (results, status) {
if (status === 'OK') {
resultsMap.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: resultsMap,
position: results[0].geometry.location
});
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
function makeInfoWindowEvent(map, infowindow, contentString, marker) {
google.maps.event.addListener(marker, 'click', function () {
infowindow.setContent(contentString);
infowindow.open(map, marker);
});
}
</script>
Here is the most recent update of my code. Still no worky........
<script>
var map, geocoder;
var Markers = [];
var infowindow;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: { lat: 0.0, lng: 0.0 },
zoom: 12
});
infowindow = new google.maps.InfoWindow();
if (!Modernizr.geolocation) {
alert("Your browser sucks. Get a new one, maybe one that is up to date and supports GPS.")
return;
}
else {
navigator.geolocation.getCurrentPosition(show_map);
}
}
function show_map(position) {
map.setZoom(12);
var Latitude = position.coords.latitude;
var Longitude = position.coords.longitude;
map.setCenter({ lat: Latitude, lng: Longitude });
var bounds = map.getBounds();
var url = "/api/xxxxxxx/yyyyyyyyyy";
var lowerLeft = bounds.getSouthWest();
var upperRight = bounds.getNorthEast();
var lat0 = lowerLeft.lat();
var lng0 = lowerLeft.lng();
var lat1 = upperRight.lat();
var lng1 = upperRight.lng();
var geocoder = new google.maps.Geocoder();
var data = { LowerLeftLat: lat0, LowerLeftLng: lng0, UpperRightLat: lat1, UpperRightLng: lng1 };
$.get(url, data, function (result) {
for (var i = 0; i < result.length; i++) {
var address = result[i].Address1 + " " +
(result[i].Address2 != null ? result[i].Address2 : "") +
" " + result[i].City + " " + result[i].Province + " " +
result[i].PostalCode + " " + result[i].Country;
var marker = new google.maps.Marker({
position: geocodeAddress(geocoder, map, address),
map: map,
title: address,
content: address
});
makeInfoWindowEvent(infowindow, "test" + i, marker);
}
});
}
function geocodeAddress(geocoder, resultsMap, address) {
geocoder.geocode({ 'address': address }, function (results, status) {
if (status === 'OK') {
resultsMap.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: resultsMap,
position: results[0].geometry.location
});
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
function makeInfoWindowEvent(infowindow, contentString, marker) {
(function (zinfowindow, zcontentString, zmarker) {
zinfowindow.setContent(zcontentString);
google.maps.event.addListener(zmarker, 'click', function () {
zinfowindow.open(map, zmarker);
});
})(infowindow, contentString, marker);
}
</script>
function makeInfoWindowEvent(map, infowindow, contentString, marker) {
infowindow.setContent(contentString);
google.maps.event.addListener(marker, 'click', function () {
infowindow.open(map, marker);
});
}
Your code crash because when the listener is calling, the value of marker and infowindow have already changed. You can try something like this (just change the makeInfoWindowEvent function):
function makeInfoWindowEvent(map, infowindow, contentString, marker) {
google.maps.event.addListener(marker, 'click', function () {
infowindow.setContent(contentString);
infowindow.open(map, marker);
console.log (contentString);
console.log (marker);
});
}
Normally, the output will be always the same for contentString and marker.
In order to pass the real value of the marker, contentString and infowindow, you have to create an IIFE. Like this, the value of the variables will be copy inside the function:
function makeInfoWindowEvent(map, infowindow, contentString, marker) {
(function (zinfowindow, zcontentString, zmarker) {
zinfowindow.setContent(zcontentString);
google.maps.event.addListener(zmarker, 'click', function () {
zinfowindow.open(map, zmarker);
});
})(infowindow, contentString, marker);
}
However, you do not need to pass map as parameter because the value of map is always the same.
Tell me if you have some questions.

Google Maps Javascript not getting Coordinates of user

This javascript wont get the coordinates of the user
(this is a html, js and css application only)
(the area with Bold and Italic text, is the one supposed to get the coordinates from the client)
I have tried different soloutions, and they wont work, + it doesnt show the ones if the user is within 25km
center: new google.maps.LatLng(val(coords.latitude),val(coords.longitude)),
<script type="text/javascript">
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,
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: 8,
center: new google.maps.LatLng(val(coords.latitude),val(coords.longitude)),
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("markers.xml", function(doc) {
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("lng"));
var point = new google.maps.LatLng(lat,lng);
var id = markers[i].getAttribute("id");
var sted = markers[i].getAttribute("sted");
var html="<b>"+sted+"</b><br>"+id;
var marker = createMarker(point,sted+" "+id,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>
You can user a simple JS function for that.
<script>
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showLatLng);
} else {
alert("Geolocation is not supported by this browser.");
}
}
function showLatLng(location) {
alert("Latitude: " + location.coords.latitude +
"Longitude: " + location.coords.longitude);
}
</script>
Hope it helps

Google maps markers from xml working in Chrome, not Firefox/IE

I've got a custom google map that loads a bunch of markers from an xml doc and creates a sidebar list of all the markers as well. It works fine in Chrome but but the sidebar and markers don't load in Firefox or IE. I'm using the latest versions of all browsers on a Windows7 machine.
--I edited this to add the xml parser code since that may be the problem. I don't even remember where I got this parser code but it has been(and still is) working fine on another project with pretty similar code.
javascript...
var side_bar_html = "";
var routes = {
y: {
name: "Winter Routes",
url: "http://www.huts.org/Tests/Maps/GPSTracks/10thsystemHutsYurtsMap.kml"
},
};
var gmarkers = [];
var map = null;
// A function to create the marker and set up the event window function
function createMarker(latlng, name, html) {
var contentString = html;
var marker = new google.maps.Marker({
position: latlng,
icon: 'images/marker2_ltblue.png',
map: map,
suppressInfoWindows: true,
zIndex: Math.round(latlng.lat()*-100000)<<5
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(contentString);
infowindow.open(map,marker);
});
google.maps.event.addListener(marker, 'click', function() {
// map.setZoom(9);
map.setCenter(marker.getPosition());
});
// save the info we need to use later for the side_bar
gmarkers.push(marker);
// add a line to the side_bar html
side_bar_html += '<a href="javascript:myclick(' + (gmarkers.length-1) + ')" onmouseover="gmarkers['+ (gmarkers.length-1) +'].setAnimation(google.maps.Animation.BOUNCE)" onmouseout="gmarkers['+ (gmarkers.length-1) +'].setAnimation(null)">' + name + '<\/a><br>';
}
// This function picks up the click and opens the corresponding info window
function myclick(i) {
google.maps.event.trigger(gmarkers[i], "click");
}
function initialize() {
// create the map
var myOptions = {
zoom: 9,
center: new google.maps.LatLng(39.369804, -106.388725),
mapTypeControl: true,
mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU},
navigationControl: true,
mapTypeId: google.maps.MapTypeId.TERRAIN
}
map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
google.maps.event.addListener(map, 'click', function() {
infowindow.close();
});
// Read the data from example.xml
downloadUrl("gMapsHuts.xml", function(doc) {
var xmlDoc = xmlParse(doc);
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 google.maps.LatLng(lat,lng);
var name = markers[i].getAttribute("label");
var html = GXml.value(markers[i].getElementsByTagName("infowindow")[0]);
var category = markers[i].getAttribute("category");
var season = markers[i].getAttribute("season");
// create the marker
var marker = createMarker(point,name,html,category);
}
// put the assembled side_bar_html contents into the side_bar div
document.getElementById("side_bar").innerHTML = side_bar_html;
});
createRouteTogglers();
}
// the important function... routes[id].xxxxx refers back to the top
function toggleRoute(checked, id) {
if (checked) {
var layer = new google.maps.KmlLayer(routes[id].url, {
preserveViewport: true,
suppressInfoWindows: false
});
// store kml as obj
routes[id].obj = layer;
routes[id].obj.setMap(map);
}
else {
routes[id].obj.setMap(null);
delete routes[id].obj;
}
};
// create the Routes controls
function createRouteTogglers() {
var html = "<form><ul>";
for (var prop in routes) {
html += "<li id=\"selector-" + prop + "\"><input type='checkbox' id='" + prop + "'" +
" onclick='highlight(this,\"selector-" + prop + "\"); toggleRoute(this.checked, this.id)' \/>" +
routes[prop].name + "<\/li>";
}
html += "<\/ul><\/form>";
document.getElementById("routeLayers").innerHTML = html;
};
// Append Class on Select
function highlight(box, listitem) {
var selected = 'selected';
var normal = 'normal';
document.getElementById(listitem).className = (box.checked ? selected: normal);
};
var infowindow = new google.maps.InfoWindow(
{
size: new google.maps.Size(150,50)
});
xml parser...
function GXml(){}
GXml.value=value;
GXml.parse=parse;
function value(node){
if(!node){
return"";
}
var retStr="";
if(node.nodeType==3||node.nodeType==4||node.nodeType==2){
retStr+=node.nodeValue;
}else if(node.nodeType==1||node.nodeType==9||node.nodeType==11){
for(var i=0;i<node.childNodes.length;++i){
retStr+=arguments.callee(node.childNodes[i]);
}
}
return retStr;
}
function parse(textDoc){
try{
if(typeof ActiveXObject!="undefined"&&typeof GetObject!="undefined"){
var b=new ActiveXObject("Microsoft.XMLDOM");
b.loadXML(textDoc);
return b;
}else if(typeof DOMParser!="undefined"){
return(new DOMParser()).parseFromString(textDoc,"text/xml");
}else{
return Wb(textDoc);
}
}
catch(c){
P.incompatible("xmlparse");
}
try{
return Wb(textDoc);
}
catch(c){
P.incompatible("xmlparse");
return document.createElement("div");
}
}
function P(){}
P.write=function(a,b){}
;P.writeRaw=function(a){}
;P.writeXML=function(a){}
;P.writeURL=function(a){}
;P.dump=function(a){}
;P.incompatible=function(){}
;P.clear=function(){}
;
function Wb(a){
return null;
}

Categories

Resources