Sidebar On Click Infowindow Open, Data retrieved by XML - google-maps-api-3

I have retrieved the data from xml..Generated Sidebar. I want to open infowindow on click on the sidebar.. Tried so many examples and codes but not succeeded... Can you please suggest what should be function declaration for myclick function:
Below i am mentioning my code...I will be grateful to you if any one can help!!
var gmarkers = [];
function load() {
var side_bar_html = "<div class=\"pro_curved-hz-2\"><div class=\"pro_text-shadow\" style=\"height: 250px;overflow-x:hidden;overflow-y: scroll;\">";
var map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(<?php echo $SelectedLatitude; ?>,<?php echo $SelectedLongitude; ?>),
zoom: <?php echo $Zoom; ?>,
mapTypeId: 'roadmap'
});
var infoWindow = new google.maps.InfoWindow;
// Change this depending on the name of your PHP file
downloadUrl("/map.php", function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
var count=markers.length;
if(count>0)
side_bar_html += '<span class=\"pro_info pro_info-indent pro_info_success\">' + count + ' result found!! </span><div class=clear></div>';
else
side_bar_html += '<span class=\"pro_info pro_info-indent pro_info_warning\"> No Result found!! </span><div class=clear></div>';
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 link= '/Place';
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var html = "<b>" + name + "</b> <br/>" + address;
var Mainicon = customMainIcons[type] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
icon: Mainicon.icon,
shadow: Mainicon.shadow,
animation: google.maps.Animation.DROP,
});
gmarkers[i] = marker;
side_bar_html += '<div class=\"pro_curved-hz-2-1\" onclick="myclick('+i+');" onmouseover="mymouseover('+i+');" onmouseout="mymouseout('+i+');" ><div class=\"pro_text-shadow\"><a href=' + link + '>' + name + '</a><br>' + address + '</div></div>';
bindInfoWindow(marker, map, infoWindow, html, side_bar_html);
}
side_bar_html += "</div></div>";
});
}
function myclick(index) {
}
function mymouseover(i) {
gmarkers[i].setAnimation(google.maps.Animation.BOUNCE);
}
function mymouseout(i) {
gmarkers[i].setAnimation(null);
}
function bindInfoWindow(marker, map, infoWindow, html, side_bar_html) {
document.getElementById("SideBar").innerHTML = side_bar_html;
google.maps.event.addListener(marker,'mouseover', function() {
//marker.setAnimation(google.maps.Animation.BOUNCE);
//setTimeout(function(){ marker.setAnimation(null); }, 750);
infoWindow.setContent(html);
infoWindow.open(map, marker);
});
google.maps.event.addListener(marker,'mouseout', function() {
infoWindow.setContent(html);
infoWindow.close(map, marker);
});
var p=<?php echo $Zoom; ?>;
google.maps.event.addListener(marker, 'click', function() {
p+=1;
if(p>=20)
{
infoWindow.setContent(html);
infoWindow.open(map, marker);
}
else
{
map.setZoom(p);
map.setCenter(marker.getPosition());
}
});
}
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() {}
//]]>

Here is an example that does what you are requesting (with function closure and a createMarker function).
Here is an example that doesn't use function closure.

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();

Google Map Direction service Route

I want to draw the shortest path map route miles between the two points.Using the Javascript - directionsService.route
As click on first time map it creates start point as click second time on map it creates second point on it and draws route
var map;
var infowindow = new google.maps.InfoWindow();
var wayA;[![enter image description here][1]][1]
var wayB;
var geocoder = new google.maps.Geocoder();
var directionsDisplay = new google.maps.DirectionsRenderer({
suppressMarkers: true,
panel: document.getElementById('right-panel'),
draggable: true
});
var directionsService = new google.maps.DirectionsService();
var data = {};
initMap();
function initMap() {
debugger;
map = new google.maps.Map(document.getElementById('rmap'), {
center: new google.maps.LatLng(23.030357, 72.517845),
zoom: 15
});
google.maps.event.addListener(map, "click", function (event) {
if (!wayA) {
wayA = new google.maps.Marker({
position: event.latLng,
map: map,
icon: "https://chart.googleapis.com/chart?chst=d_map_pin_letter&chld=S|00FF00|000000"
});
} else {
if (!wayB) {
debugger;
wayB = new google.maps.Marker({
position: event.latLng,
map: map,
icon: "https://chart.googleapis.com/chart?chst=d_map_pin_letter&chld=E|FF0000|000000"
});
calculateAndDisplayRoute(directionsService, directionsDisplay, wayA, wayB);
}
}
});
}
function computeTotalDistance(result) {
var total = 0;
var myroute = result.routes[0];
for (var i = 0; i < myroute.legs.length; i++) {
total += myroute.legs[i].distance.value;
}
total = total / 1000;
return total;
}
function computeTotalDuration(result) {
var total = 0;
var myroute = result.routes[0].legs[0].duration.text;
return myroute;
}
function calculateAndDisplayRoute(directionsService, directionsDisplay, wayA, wayB) {
debugger;
directionsDisplay.setMap(map);
google.maps.event.addListener(directionsDisplay, 'directions_changed', function () {
debugger;
calculateAndDisplayRoute(directionsService, directionsDisplay.getDirections(), wayA, wayB);
});
directionsService.route({
origin: wayA.getPosition(),
destination: wayB.getPosition(),
optimizeWaypoints: true,
travelMode: 'DRIVING'
}, function (response, status) {
if (status === 'OK') {
debugger;
var route = response.routes[0];
wayA.setMap(null);
wayB.setMap(null);
pinA = new google.maps.Marker({
position: route.legs[0].start_location,
map: map,
icon: "https://chart.googleapis.com/chart?chst=d_map_pin_letter&chld=S|00FF00|000000"
}),
pinB = new google.maps.Marker({
position: route.legs[0].end_location,
map: map,
icon: "https://chart.googleapis.com/chart?chst=d_map_pin_letter&chld=E|FF0000|000000"
});
google.maps.event.addListener(pinA, 'click', function () {
infowindow.setContent("<b>Route Start Address = </b>" + route.legs[0].start_address + " <br/>" + route.legs[0].start_location);
infowindow.open(map, this);
});
google.maps.event.addListener(pinB, 'click', function () {
debugger;
infowindow.setContent("<b>Route End Address = </b>" + route.legs[0].end_address + " <br/><b>Distance=</b> " + computeTotalDistance(directionsDisplay.getDirections()) + " Km <br/><b>Travel time=</b> " + computeTotalDuration(directionsDisplay.getDirections()) + " <br/> " + route.legs[0].end_location);
infowindow.open(map, this);
});
} else {
window.alert('Directions request failed due to ' + status);
}
directionsDisplay.setDirections(response);
});
}

close InfoWindow before open another

I have a problem with InfoWindow. I have an ajax function that retrieves data via JSON, but I can not get close InfoWindow automatically when you open another.
My code is this:
var mapOptions = {
center: new google.maps.LatLng(44.49423583832911, 11.346244544982937),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("mappa_locali"),mapOptions);
$.ajax({
type:'GET',
url:"locali_json.php"+urlz,
success:function(data){
var json = JSON.parse(data);
for (var i=0; i<json.length; i++) {
point = new google.maps.LatLng(json[i].latitudine,json[i].longitudine);
var infowindow = new google.maps.InfoWindow;
infowindow.setContent(''+json[i].nome_locale+'<br>'+json[i].address);
addMarkerz(point,infowindow);
}
}
})
}
function addMarkerz(point,infowindow) {
position: point,
map: map
});
google.maps.event.addListener(marker,'mouseover',infoCallback(infowindow, marker));
markers.push(marker);
infos.push(infowindow);
}
function infoCallback(infowindow, marker) {
return function() {
infowindow.close();
infowindow.open(map, marker);
};
}
Does anyone know where decreased mistake? Or do you have any advice for me?
The suggestion is only create one infowindow (in the global scope), reuse it and change its contents when a marker is clicked, close it if the user clicks on the map.
code snippet (removes the dependency on the AJAX call):
// global variables
var map;
var markers = [];
var infowindow = new google.maps.InfoWindow();
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(44.49423583832911, 11.346244544982937),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("mappa_locali"), mapOptions);
var json = JSON.parse(data);
for (var i = 0; i < json.length; i++) {
point = new google.maps.LatLng(json[i].latitudine, json[i].longitudine);
var infowindowHtml = '' + json[i].nome_locale + '<br>' + json[i].address;
addMarkerz(point, infowindowHtml);
}
}
function addMarkerz(point, infowindowHtml) {
var marker = new google.maps.Marker({
position: point,
map: map
});
google.maps.event.addListener(marker, 'mouseover', infoCallback(infowindowHtml, marker));
markers.push(marker);
}
function infoCallback(infowindowHtml, marker) {
return function() {
infowindow.close();
// update the content of the infowindow before opening it
infowindow.setContent(infowindowHtml)
infowindow.open(map, marker);
};
}
var data = JSON.stringify([{
latitudine: 44.494887,
longitudine: 11.3426163,
id_locale: "0",
nome_locale: "Bologna",
address: "Bologna, Italy"
}, {
latitudine: 44.4946615,
longitudine: 11.314634999999953,
id_locale: "0",
nome_locale: "Quartiere Saragozza",
address: "Quartiere Saragozza, Bologna, Italy"
}]);
google.maps.event.addDomListener(window, "load", initialize);
html,
body,
#mappa_locali {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div id="mappa_locali"></div>
function infoCallback(infowindow, marker) {
return function() {
infowindow.close();
infowindow.open(map, marker);
};
}
should be changed to
function infoCallback(infowindow, marker) {
return function() {
//Close active window if exists
if (activeWindow != null) {
activeWindow.close();
}
//Open new window
infowindow.open(map,marker);
//Store new window in global variable
activeWindow = infowindow;
};
}
and declare activeWindow as a global variable in your .js file as var activeWindow.
I think I have a simple solution. I just save the last open mark. On the next click first of all I close the last mark.
var markers = [];
var infowindows = [];
function addMarkes(facilityID) {
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < variants.length; i++) {
var v = variants[i];
var position = new google.maps.LatLng(v.Lat, v.Long);
bounds.extend(position);
markers[i] = new google.maps.Marker({
position: position,
title: v.Title,
map: map,
animation: google.maps.Animation.DROP,
icon: v.Icon,
infoWindowIndex: i //synchronize with infoWindows
});
var localContent = '<div><span class="address">' + v.Address + '</span></div>';
infowindows[i] = new google.maps.InfoWindow({
content: localContent
});
//Just for multiple marks.
if (variants.length > 0) {
var lastOpen = -1; //Save the last open mark
google.maps.event.addListener(markers[i], 'click', function (innerKey) {
return function () {
//Close the last mark.
if (lastOpen > -1) {
infowindows[lastOpen].close();
}
infowindows[innerKey].open(map, markers[innerKey]);
lastOpen = innerKey;
}
}(i));
}
}
map.fitBounds(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>

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