Problems Getting XML data with custom icon to show in Google Map on my site - google-maps-api-3

Hello all I am trying to resolve an issue with getting my XML data to show in a map. I am still learning the code, but perhaps someone could help me determine why the icons / data will not show.
Here is a sample of my XML:
<?xml version="1.0"?>
<markers>
<marker
id="461"
name="Pilot Travel Center"
address="I-20 / 59, Exit 123"
city="Birmingham"
state="AL"
zip="35204"
phone="xxx-xxx-xxxx"
fax="xxx-xxx-xxxx"
manager="Joe"
lat="33.529307"
lng="-86.852215"
url="http://www.pilotflyingj.com"
type="restaurant"/>
<marker
id="1402"
name="Flying J Travel Plaza"
address="Ross Clark Highway / Highway 231"
city="Dothan"
state="AL"
zip="36301"
phone="xxx-xxx-xxxx"
fax="xxx-xxx-xxxx"
manager="Johnny"
lat="31.192005"
lng="-85.399838"
url="http://www.pilotflyingj.com"
type="restaurant"/>
</markers>
and here is the google API portion
<script>
var customIcons = {
restaurant: {
icon: 'ts_images/cat_scales.png',
},
bar: {
icon: 'ts_images/xx.png',
}
};
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
center: new google.maps.LatLng(39.809734, -98.555620),
zoom: 4
});
var infoWindow = new google.maps.InfoWindow;
// Change this depending on the name of your PHP or XML file
downloadUrl('xml/cat_scales.xml', function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName('marker');
Array.prototype.forEach.call(markers, function(markerElem) {
var id = markerElem.getAttribute('id');
var name = markerElem.getAttribute('name');
var address = markerElem.getAttribute('address');
var city = markerElem.getAttribute('city');
var state = markerElem.getAttribute('state');
var zip = markerElem.getAttribute('zip');
var phone = markerElem.getAttribute('phone');
var fax = markerElem.getAttribute('fax');
var manager = markerElem.getAttribute('manager');
var url = markerElem.getAttribute('url');
var phone = markerElem.getAttribute('phone');
var type = markerElem.getAttribute('type');
var point = new google.maps.LatLng(
parseFloat(markerElem.getAttribute('lat')),
parseFloat(markerElem.getAttribute('lng')));
var infowincontent = document.createElement('div');
var strong = document.createElement('strong');
strong.textContent = name
infowincontent.appendChild(strong);
infowincontent.appendChild(document.createElement('br'));
var text = document.createElement('text');
text.textContent = address
infowincontent.appendChild(text);
var icon = customIcons[type] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
icon: icon.icon
});
marker.addListener('click', function() {
infoWindow.setContent(infowincontent);
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>
I have searched but cannot determine what the issue is. I would greatly appreciate the help. Thank You.

Use the full URL of the custom icons. It needs to be a complete URL publicly available on the web (pointing to your webserver where you have your custom icon).
for example (using icons on my server):
http://www.geocodezip.com/mapIcons/marker_red.png
So define the custom icon structure like this:
var customIcons = {
restaurant: {
icon: 'http://www.geocodezip.com/mapIcons/marker_red.png',
},
bar: {
icon: 'http://www.geocodezip.com/mapIcons/marker_blue.png',
}
};
proof of concept fiddle
code snippet:
var customIcons = {
restaurant: {
icon: 'http://www.geocodezip.com/mapIcons/marker_red.png',
},
bar: {
icon: 'http://www.geocodezip.com/mapIcons/marker_blue.png',
}
};
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
center: new google.maps.LatLng(39.809734, -98.555620),
zoom: 4
});
var infoWindow = new google.maps.InfoWindow();
// Change this depending on the name of your PHP or XML file
// downloadUrl('xml/cat_scales.xml', function(data) {
// var xml = data.responseXML;
var xml = xmlParse(xmlStr);
var markers = xml.documentElement.getElementsByTagName('marker');
Array.prototype.forEach.call(markers, function(markerElem) {
var id = markerElem.getAttribute('id');
var name = markerElem.getAttribute('name');
var address = markerElem.getAttribute('address');
var city = markerElem.getAttribute('city');
var state = markerElem.getAttribute('state');
var zip = markerElem.getAttribute('zip');
var phone = markerElem.getAttribute('phone');
var fax = markerElem.getAttribute('fax');
var manager = markerElem.getAttribute('manager');
var url = markerElem.getAttribute('url');
var type = markerElem.getAttribute('type');
var point = new google.maps.LatLng(
parseFloat(markerElem.getAttribute('lat')),
parseFloat(markerElem.getAttribute('lng')));
var infowincontent = document.createElement('div');
var strong = document.createElement('strong');
strong.textContent = name
infowincontent.appendChild(strong);
infowincontent.appendChild(document.createElement('br'));
var text = document.createElement('text');
text.textContent = address
infowincontent.appendChild(text);
var icon = customIcons[type] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
icon: icon.icon
});
marker.addListener('click', function() {
infoWindow.setContent(infowincontent);
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() {}
google.maps.event.addDomListener(window, 'load', initMap);
function xmlParse(str) {
if ((typeof ActiveXObject != 'undefined') || ("ActiveXObject" in window)) {
var doc = new ActiveXObject('Microsoft.XMLDOM');
doc.loadXML(str);
return doc;
}
if (typeof DOMParser != 'undefined') {
return (new DOMParser()).parseFromString(str, 'text/xml');
}
return document.createElement('div', null);
}
var xmlStr = '<?xml version="1.0"?><markers><marker id="461" name="Pilot Travel Center" address="I-20 / 59, Exit 123" city="Birmingham" state="AL" zip="35204" phone="xxx-xxx-xxxx" fax="xxx-xxx-xxxx" manager="Joe" lat="33.529307" lng="-86.852215" url="http://www.pilotflyingj.com" type="restaurant"/><marker id="1402" name="Flying J Travel Plaza" address="Ross Clark Highway / Highway 231" city="Dothan" state="AL" zip="36301" phone="xxx-xxx-xxxx" fax="xxx-xxx-xxxx" manager="Johnny" lat="31.192005" lng="-85.399838" url="http://www.pilotflyingj.com" type="bar"/></markers>';
html,
body,
#map {
height: 100%;
width: 100%;
padding: 0px;
margin: 0px;
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id='map'></div>

Related

Code works in EDIT view and not SAVED page

My mission: Create a map from list such as :
When editing a SharePoint page (edit mode/view) the map throws no errors in the console. But as I go to view the final saved page the map I get this error in the console:
Event Page.aspx:668 Uncaught TypeError: Cannot read property 'get_current' of undefined
at retrieveListItems (Event Page.aspx:668)
at Event Page.aspx:789
This error points to this line :
var clientContext = new SP.ClientContext.get_current();
It seems like the PAGE is missing some resources that get added when I'm in EDIT MODE.
This code gets the info from the list to pass to the map script.
function retrieveListItems() {
var listName = "North East Events";
var clientContext = new SP.ClientContext.get_current();
var oList = clientContext.get_web().get_lists().getByTitle(listName);
this.website = clientContext.get_web();
var camlQuery = new SP.CamlQuery();
camlQuery.set_viewXml('<View><Query><Where><Geq><FieldRef Name=\'ID\'/>' +
'<Value Type=\'Number\'>1</Value></Geq></Where></Query><RowLimit>50</RowLimit></View>');
collListItem = oList.getItems(camlQuery);
clientContext.load(this.website);
clientContext.load(this.collListItem);
clientContext.executeQueryAsync(Function.createDelegate(this, onQuerySucceeded), Function.createDelegate(this, onQueryFailed));
}
function onQuerySucceeded(sender, args) {
var geocoder;
var map;
var bounds = new google.maps.LatLngBounds();
var listItemInfo = '';
var locations = [];
var listItemEnumerator = collListItem.getEnumerator();
while (listItemEnumerator.moveNext()) {
var oListItem = listItemEnumerator.get_current();
var eventName = oListItem.get_item('Title');
var eventAddress = oListItem.get_item('WorkAddress');
var eventURL = website.get_url() + '/' + 'Lists/North East Reports/DispForm.aspx?ID=' + oListItem.get_id();
var newLocations = [eventName, eventAddress, eventURL];
locations.push(newLocations);
}
google.maps.event.addDomListener(window, "load", initialize);
function initialize() {
map = new google.maps.Map(
document.getElementById("map_canvas"), {
center: new google.maps.LatLng(37.4419, -122.1419),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
geocoder = new google.maps.Geocoder();
for (i = 0; i < locations.length; i++) {
geocodeAddress(locations, i);
}
}
function geocodeAddress(locations, i) {
var title = locations[i][0];
var address = locations[i][1];
var url = locations[i][2];
geocoder.geocode({
'address': locations[i][1]
},
function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var marker = new google.maps.Marker({
icon: 'http://maps.google.com/mapfiles/ms/icons/blue.png',
map: map,
position: results[0].geometry.location,
title: title,
animation: google.maps.Animation.DROP,
address: address,
url: url
})
infoWindow(marker, map, title, address, url);
bounds.extend(marker.getPosition());
map.fitBounds(bounds);
} else {
alert("geocode of " + address + " failed:" + status);
}
});
}
function infoWindow(marker, map, title, address, url) {
google.maps.event.addListener(marker, 'click', function() {
var html = "<div><h3>" + title + "</h3><p>" + address + "<br></div><a href='" + url + "'>View location</a></p></div>";
iw = new google.maps.InfoWindow({
content: html,
maxWidth: 350
});
iw.open(map, marker);
});
}
function createMarker(results) {
var marker = new google.maps.Marker({
icon: 'http://maps.google.com/mapfiles/ms/icons/blue.png',
map: map,
position: results[0].geometry.location,
title: title,
animation: google.maps.Animation.DROP,
address: address,
url: url
})
bounds.extend(marker.getPosition());
map.fitBounds(bounds);
infoWindow(marker, map, title, address, url);
return marker;
}
}
function onQueryFailed(sender, args) {
alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}
retrieveListItems();

Implementing google place autocomplete

This is my code for places autocomplete and search.
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&libraries=places">
</script>
<script>
var geocoder;
var map;
function initialize() {
var input = document.getElementById('address');
var options = {
componentRestrictions: {country: "in"}
};
var autocomplete = new google.maps.places.Autocomplete(input,options);
geocoder = new google.maps.Geocoder();
//var latlng = new google.maps.LatLng(18.52043030000, 73.85674369999);
var mapOptions = {
zoom: 15,
//center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
}
map = new google.maps.Map(document.getElementById('googleMap'), mapOptions);
}
function codeAddress() {
var address = document.getElementById('address').value;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
This is my html code.
<input id="address" type="textbox" size="30">
<input type="button" value="Search" onclick="codeAddress()">
It is working fine but I dont want to user to click the button. When suggestions appeared, and when user select any of suggestion options, map will have to navigate to that place. How do I do this???
When User select any option from dropdown, map should navigate to that place.
Take a look at this example and the implementation of the place_changed event.
var place = autocomplete.getPlace();
// If the place has a geometry, then present it on a map.
if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
} else {
map.setCenter(place.geometry.location);
}
This way you can pan the map to the location of the autocomplete result.
This is my working code..
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&libraries=places">
</script>
<script>
var geocoder;
var map;
function initialize() {
var input = document.getElementById('address');
var options = {
componentRestrictions: {country: "in"}
};
var autocomplete = new google.maps.places.Autocomplete(input,options);
geocoder = new google.maps.Geocoder();
//var latlng = new google.maps.LatLng(18.52043030000, 73.85674369999);
var mapOptions = {
zoom: 15,
//center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
}
map = new google.maps.Map(document.getElementById('googleMap'), mapOptions);
var infowindow = new google.maps.InfoWindow();
var marker = new google.maps.Marker({
map: map,
anchorPoint: new google.maps.Point(0, -29)
});
google.maps.event.addListener(autocomplete, 'place_changed', function() {
infowindow.close();
marker.setVisible(false);
var place = autocomplete.getPlace();
if (!place.geometry) {
return;
}
if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
} else {
map.setCenter(place.geometry.location);
map.setZoom(17); // Why 17? Because it looks good.
}
marker.setIcon(/** #type {google.maps.Icon} */({
url: place.icon,
size: new google.maps.Size(71, 71),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(17, 34),
scaledSize: new google.maps.Size(35, 35)
}));
marker.setPosition(place.geometry.location);
marker.setVisible(true);
var address = '';
if (place.address_components) {
address = [
(place.address_components[0] && place.address_components[0].short_name || ''),
(place.address_components[1] && place.address_components[1].short_name || ''),
(place.address_components[2] && place.address_components[2].short_name || '')
].join(' ');
}
infowindow.setContent('<div><strong>' + place.name + '</strong><br>' + address);
infowindow.open(map, marker);
});
}
function codeAddress() {
var address = document.getElementById('address').value;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
Now user can select option from dropdown and map will navigate to that place. And also on search button click.
Hope this might help you
function initialize(){
var mapOptions = {//Map Properties
zoom:12,
center: Bangalore
};
googleMap = new google.maps.Map(document.getElementById('map-holder'),mapOptions);//map-holder is a div which holds map in my html
var defaultBounds = new google.maps.LatLngBounds(//bounds for Bengaluru
new google.maps.LatLng(12.7342888,77.3791981),
new google.maps.LatLng(13.173706,77.8826809)
);
googleMap.fitBounds(defaultBounds);
var input = (document.getElementById('searchInput'));//search input element
googleMap.controls[google.maps.ControlPosition.TOP_LEFT].push(input);//binding it to map
var searchBox = new google.maps.places.SearchBox((input));
google.maps.event.addListener(searchBox, 'places_changed', function() {//triggers when search is performed
var places = searchBox.getPlaces();
if (places.length == 0) {
return;
}
var bounds = new google.maps.LatLngBounds();
for (var i = 0, place; place = places[i]; i++) {
bounds.extend(place.geometry.location);
//googleMap.fitBounds(place.geometry.viewport);
}
googleMap.fitBounds(bounds);
});
google.maps.event.addListener(googleMap, 'bounds_changed', function() {
var bounds = googleMap.getBounds();
searchBox.setBounds(bounds);
})
}

Can't close infowindow and display street view

I'm trying to close an infowindow wich displays a streetview. When I click on the map, the infowindow is not closed. Also when I click over other marker an infowindow is opened but the streetview opens in the previous infowindow. So I need that the infowindow get closed and displays the streetview. Here is the code: thank you for your help.
Best regards.
function paradascamiones() {
google.maps.event.addListener(map, 'click', function() {
infowindow.close();
});
var Boton = document.getElementById('Boton').value;
var textboxImei = document.getElementById('imei').value;
var textboxFecha = document.getElementById('fecha').value;
var textboxFechaFin = document.getElementById('fechaFin').value;
var textboxDesdeHora = document.getElementById('desdeHora').value;
var textboxHastaHora = document.getElementById('hastaHora').
downloadUrl("paradas.asp?imei="+textboxImei+"&fecha="+textboxFecha+" "+textboxDesdeHora+"&fechaFin="+textboxFechaFin+" "+textboxHastaHora,
function(data) {
var xml = xmlParse(data);
var markersParadas = xml.documentElement.getElementsByTagName("marker");
var position = [];
for (var i = 0; i < markersParadas.length; i++) {
var lat = parseFloat(markersParadas[i].getAttribute("lat"));
var lng = parseFloat(markersParadas[i].getAttribute("lng"));
var myLatlngParadas = new google.maps.LatLng(lat, lng);
var fechaInicio = markersParadas[i].getAttribute("fechaInicio");
var fechaFinal = markersParadas[i].getAttribute("fechaFinal");
var diferencia = markersParadas[i].getAttribute("diferencia");
var datearray = diferencia.split("/");
var newDate = datearray[1] + '/' + datearray[0] + '/' + datearray[2];
var aFecha = new Date(newDate);
var hours = aFecha.getHours();
var minutes = aFecha.getMinutes();
var seconds = aFecha.getSeconds();
var markerParadas = createMarkerParadas(myLatlngParadas, hours, minutes, seconds, fechaInicio);
myMarkersParadas.push(markerParadas);
}//finish loop
}); //end download url
}
function createMarkerParadas(myLatlngParadas, hours, minutes, seconds, fechaInicio) {
var contentString = '<div id="content" style="width:350px;height:300px;"> </div>';
var infoWindow = new google.maps.InfoWindow({
content: contentString
});
var image2 = '/artworks/icons/stop.png';
var markerParadas = new google.maps.Marker({
position: myLatlngParadas,
map: map,
title: " my info ",
icon: image2
});
google.maps.event.addListener(markerParadas, "click", function () {
infoWindow.open(map, markerParadas);
var pano = null;
google.maps.event.addListener(infoWindow, 'domready', function () {
if (pano != null) {
pano.unbind("position");
pano.setVisible(false);
}
pano = new google.maps.StreetViewPanorama(document.getElementById("content"), {
navigationControl: true,
enableCloseButton: false,
addressControl: true,
linksControl: false
});
pano.bindTo("position", markerParadas);
pano.setVisible(true);
});
google.maps.event.addListener(infoWindow, 'closeclick', function () {
pano.unbind("position");
pano.setVisible(false);
pano = null;
});
});
return markerParadas;
}
In your code, at least you should change that defining the infowindow variable as global scope.
your code
function createMarkerParadas() {
var infoWindow = new google.maps.InfoWindow({
content : contentString
});
...
}
Change to like this;
<script type="text/javascript">
var map, infowindow;
...
function createMarkerParadas() {
infoWindow = new google.maps.InfoWindow({
content : contentString
});
....
}
</script>

update infowindows when calling again a xml file

Good morning.
I have the next code which put some markers in a map from a xml file, every 5 seconds I call again the xml file and I update the position of the markers, but the problem is that the infowindows are not updated. Does anyone knows how to update them=
Here you have the code:
//<![CDATA[
var side_bar_html = "";
var gmarkers = [];
var map = null;
var markerclusterer = null;
function myclick(i) {
google.maps.event.trigger(gmarkers[i], "click");
map.setZoom(map.getZoom()+2);
}
function initialize() {
// create the map
var myOptions = {
zoom: 12,
center: new google.maps.LatLng(37.169619,-3.756981),
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);
}
function getMarkers() {
google.maps.event.addListener(map, 'click', function() {
infowindow.close();
});
downloadUrl("vehiculos.asp", 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 imei = markers[i].getAttribute("imei");
var alias = markers[i].getAttribute("alias");
var speed= markers[i].getAttribute("speed");
var timestamp= markers[i].getAttribute("timestamp");
var estado= markers[i].getAttribute("estado");
var conectado= markers[i].getAttribute("conectado");
var altitude= markers[i].getAttribute("altitude");
var angle= markers[i].getAttribute("angle");
var html="<b>"+alias+" "+speed+" km/h <br/> "+timestamp;
var marker = createMarker(point,alias+" "+imei,html,estado,alias, speed, timestamp, altitude, angle);
}
markerCluster = new MarkerClusterer(map, gmarkers);
});
}
var infowindow = new google.maps.InfoWindow(
{
size: new google.maps.Size(150,60)
});
setInterval(function updateMarkers() {
google.maps.event.addListener(map, 'click', function() {
infowindow.close();
});
downloadUrl("vehiculos.asp", 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 imei = markers[i].getAttribute("imei");
var alias = markers[i].getAttribute("alias");
var speed= markers[i].getAttribute("speed");
var timestamp= markers[i].getAttribute("timestamp");
var estado= markers[i].getAttribute("estado");
var conectado= markers[i].getAttribute("conectado");
var altitude= markers[i].getAttribute("altitude");
var angle= markers[i].getAttribute("angle");
var html="<b>"+alias+" a "+speed+" km/h <br/> "+timestamp;
var newLatLng = gmarkers[i].setPosition(point,alias+" "+imei,html,estado,alias,speed,timestamp,altitude,angle);
}
markerCluster = new MarkerClusterer(map, gmarkers);
});
}, 5000);
//finish updateMarkers
function createMarker(latlng, imei, html, estado, alias, speed, timestamp, altitude, angle) {
if(estado == 1)
image = '/artworks/icons/truck_green3.png';
else
image = '/artworks/icons/truck_red.png';
var textoLabel= alias+" speed: "+ speed+" km/h";
var contentString = html;
var newLatLng = new MarkerWithLabel({
position: latlng,
icon: image,
// map: map,
draggable: true,
flat: true,
labelContent: textoLabel,
labelAnchor: new google.maps.Point(40, 0),
labelClass: "labels", // the CSS class for the label
labelStyle: {
opacity: 0.50
},
zIndex: Math.round(latlng.lat()*-100000)<<5
});
google.maps.event.addListener(newLatLng, 'click', function() {
infowindow.setContent(timestamp + alias);
infowindow.open(map,newLatLng);
});
gmarkers.push(newLatLng);
// side_bar_html += '<a href="javascript:myclick(' + (gmarkers.length-1) + ')">' + imei +'<\/a><br>';
}
You are not assigning the event handler in the setInterval function, so no infowindows.
Add this code to the setInterval() after creating the marker
google.maps.event.addListener(newLatLng, 'click', function() {
infowindow.setContent(timestamp + alias);
infowindow.open(map,newLatLng);
This may result in a closure problem as you are in a loop. So you can do something like the solutions in this Passing values in for loop to event listeners- Javascript.

Cannot open google map marker from sidebar list

I am working with the v3 API and trying to recreate the Store Locator sample (which is v2). I like the way the v2 version works vs the same article changed for v3 API. I have everything working with one exception: when I click the location result it does not open up the marker in the map for that location. Here is my code. I think the problem exists in the CreateSidebarEntry() function. Any help would be greatly appreciated! (you can see it in action here: http://www.webworksct.net/clients/ccparking/partners3.php - just enter "orlando" in the search box and click search to get the results, then click a location in the list on the right...nothing happens).
//<![CDATA[
var map;
var markers = [];
var infoWindow;
var sidebar;
//var locationSelect;
function load() {
map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(40, -100),
zoom: 4,
mapTypeId: 'roadmap',
mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DEFAULT}
});
infoWindow = new google.maps.InfoWindow();
sidebar = document.getElementById("sidebar");
}
function searchLocations() {
var address = document.getElementById("addressInput").value;
var geocoder = new google.maps.Geocoder();
geocoder.geocode({address: address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
searchLocationsNear(results[0].geometry.location);
} else {
alert(address + ' not found');
}
});
}
function clearLocations() {
infoWindow.close();
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(null);
}
markers.length = 0;
sidebar.innerHTML = "";
}
function searchLocationsNear(center) {
clearLocations();
var radius = document.getElementById('radiusSelect').value;
var searchUrl = 'phpsqlsearch_genxml.php?lat=' + center.lat() + '&lng=' + center.lng() + '&radius=' + radius;
downloadUrl(searchUrl, function(data) {
var xml = parseXml(data);
var markerNodes = xml.documentElement.getElementsByTagName("marker");
var bounds = new google.maps.LatLngBounds();
var sidebar = document.getElementById('sidebar');
sidebar.innerHTML = '';
if (markerNodes.length == 0) {
sidebar.innerHTML = 'No results found.';
map.setCenter(new google.maps.LatLng(40, -100), 4);
return;
}
for (var i = 0; i < markerNodes.length; i++) {
var name = markerNodes[i].getAttribute("name");
var address = markerNodes[i].getAttribute("address");
var distance = parseFloat(markerNodes[i].getAttribute("distance"));
var latlng = new google.maps.LatLng(
parseFloat(markerNodes[i].getAttribute("lat")),
parseFloat(markerNodes[i].getAttribute("lng")));
var marker = createMarker(latlng, name, address);
bounds.extend(latlng);
var sidebarEntry = createSidebarEntry(marker, name, address, distance);
sidebar.appendChild(sidebarEntry);
}
map.fitBounds(bounds);
});
}
function createMarker(latlng, name, address) {
var html = "<b>" + name + "</b> <br/>" + address;
var marker = new google.maps.Marker({
map: map,
position: latlng
});
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(html);
infoWindow.open(map, marker);
});
markers.push(marker);
}
function createSidebarEntry(marker, name, address, distance) {
var div = document.createElement('div');
var html = '<b>' + name + '</b> (' + distance.toFixed(1) + ')<br/>' + address;
div.innerHTML = html;
div.style.cursor = 'pointer';
div.style.marginBottom = '5px';
google.maps.event.addDomListener(div, 'click', function() {
google.maps.event.trigger(marker, 'click');
});
google.maps.event.addDomListener(div, 'mouseover', function() {
div.style.backgroundColor = '#eee';
});
google.maps.event.addDomListener(div, 'mouseout', function() {
div.style.backgroundColor = '#fff';
});
return div;
}
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.responseText, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function parseXml(str) {
if (window.ActiveXObject) {
var doc = new ActiveXObject('Microsoft.XMLDOM');
doc.loadXML(str);
return doc;
} else if (window.DOMParser) {
return (new DOMParser).parseFromString(str, 'text/xml');
}
}
function doNothing() {}
//]]>
return markers[markers.push(marker)-1];
works and keeps your markers array intact
I found the answer.
In this bit of code:
var marker = createMarker(latlng, name, address);
bounds.extend(latlng);
var sidebarEntry = createSidebarEntry(marker, name, address, distance);
sidebar.appendChild(sidebarEntry);
I was calling createMarker to populate the marker var. I found that it wasn't populating.
In the createMarker function, I needed to make a change so that the function returned a value: markers.push(marker); was changed to return marker; and voila!

Resources