Multiple polylines and infowindows with Google Maps V3 - google-maps

I have a map with multiple polylines and would like to open a line-specific-infowindow when clicking the line.
So far my code only shows the content of the last iteration.
I found two very nice examples of what I want but after hours of trying I am still no further.
Example 1: http://srsz750.appspot.com/api3/polylines-multiple.html
Example 2: http://www.geocodezip.com/v3_GenericMapBrowser.asp?filename=flights090414.xml
So your are my last shot :-S
Here is my code that shows only the content of the last iteration:
for (var i = 0; i < locations.length; i++) {
var route = locations[i]; // locations is an array of route-arrays.
//route is an array with details. route[0] contains the description.
var imageStart = 'img/rijder.png';
var polyOptions = {
strokeColor: '#0000FF',
strokeOpacity: 1.0,
strokeWeight: 3
}
poly = new google.maps.Polyline(polyOptions, info);
var path = poly.getPath();
//line text
var info = route[0];
google.maps.event.addListener(poly, 'click', function(event) {
infowindow.setContent(info);
infowindow.position = event.latLng;
infowindow.open(map);
});
//startmarker
var startLatLng = new google.maps.LatLng(route[1], route[2]);
var smarker = new google.maps.Marker({
position: startLatLng,
map: map,
icon: imageStart,
title: route[7],
html: route[0]
});
path.push(startLatLng);
//starttext
google.maps.event.addListener(smarker, "click", function () {
infowindow.setContent(this.html);
infowindow.open(map, this);
});
//endmarker
var endLatLng = new google.maps.LatLng(route[4], route[5]);
var emarker = new google.maps.Marker({
position: endLatLng,
map: map,
icon: imageEnd,
title: route[8],
html: route[3]
});
path.push(endLatLng);
//endtext
google.maps.event.addListener(emarker, "click", function () {
infowindow.setContent(this.html);
infowindow.open(map, this);
});
//close line and put on the map
poly.setMap(map);
}
}
And here is the code I would expect to work but all lines disappeared (only the relevant code, I also added a mouseover function):
//line text
google.maps.event.addListener(poly, 'click', (function(event,index){
return function(){
var routeinfw = locations[index];
var inf = routeinfw[0];
infowindow.setContent(inf);
infowindow.position = mouselocation;
infowindow.open(map);
};
})(event,i));
//starticon

Just like in the example you posted, create a function to create the click events listeners and call it from inside the locations loop:
function createInfoWindow(poly,content) {
google.maps.event.addListener(poly, 'click', function(event) {
infowindow.content = content;
infowindow.position = event.latLng;
infowindow.open(map);
});
}
And you can call this at the end of the loop:
createInfoWindow(poly,info);

Related

Google Nearby change type on click

I'm working on a project where I'd like to show the choosen event on google maps with some additional information. (ex. all gas stations radius 2km).
Google doesn't allow a nearby search with multiple types.
Restricts the results to places matching the specified type. Only one type may be specified (if more than one type is provided, all types following the first entry are ignored).
So for now I'd like to change the type (ex. gas_station or store) if I click to a custom button I added.
(used the google document example)
Screenshot: http://imgur.com/qYwLuw4
Question:
Which is the best way to change the type and refresh the map with the new information?
I'd like to present you our solution.
We wrote a clear() and a showType() function, which will erase all markers and let the right ones appear on click. By the way we give the button a state class called "selected" for CSS styling.
We didn't find a solution to show both (washstation AND fuelstation).
<script type="text/javascript">
var map;
var infowindow;
var service;
var eventLocation = {lat: <?= $arrCoordinates['latitude']?>, lng: <?= $arrCoordinates['longitude']?>};
var markers = [];
var wash = document.getElementById('wash'); //washbutton
var fuel = document.getElementById('fuel'); //fuelstation button
function initMap() {
map = new google.maps.Map(document.getElementById('eventmap'), {
center: eventLocation,
zoom: 13,
});
infowindow = new google.maps.InfoWindow();
service = new google.maps.places.PlacesService(map);
showType('gas_station');
fuel.classList.add("selected");
typeControl(map);
}
// Type control function
function typeControl ( map ) {
google.maps.event.addDomListener(fuel, 'click', function() {
wash.classList.remove("selected");
fuel.classList.remove("selected");
clear()
showType('gas_station')
this.classList.add("selected");
});
google.maps.event.addDomListener(wash, 'click', function() {
wash.classList.remove("selected");
fuel.classList.remove("selected");
clear()
showType('car_wash')
this.classList.add("selected");
});
}
function showType(type) {
service.nearbySearch({
location: eventLocation,
radius: 10000,
type: [type]
}, callback);
}
function clear() {
markers.forEach(marker => marker.setMap(null));
markers = [];
}
function callback(results, status) {
clear()
if (status === google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
}
createTuningEventMarker();
}
}
function createTuningEventMarker(place) {
var eventLocation = {lat: <?= $arrCoordinates['latitude']?>, lng: <?= $arrCoordinates['longitude']?>};
var eventIcon = {
url: 'https://www.foo.lol/img/icons/pin.svg',
// This marker is 20 pixels wide by 32 pixels high.
scaledSize: new google.maps.Size(60, 60),
// The origin for this image is (0, 0).
origin: new google.maps.Point(0,0),
// The anchor for this image is the base of the flagpole at (0, 32).
anchor: new google.maps.Point(30,60)
};
var marker = new google.maps.Marker({
map: map,
icon:eventIcon,
position: eventLocation
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent('<?= $event['name']?>');
infowindow.open(map, this);
});
}
function createMarker(place) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location
});
markers.push(marker);
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(place.name + "<br>Adress: " + place.vicinity);
infowindow.open(map, this);
});
}
</script>

Google maps v3 open infowindow on load

I using this technique: http://www.geocodezip.com/v3_MW_example_map2.html
I want to have the first info window open when the map loads.
I also want to be able to center the map when you click a location link.
Can anyone help?
JS:
// this variable will collect the html which will eventually be placed in the side_bar
var side_bar_html = "";
// arrays to hold copies of the markers and html used by the side_bar
// because the function closure trick doesnt work there
var gmarkers = [];
var map = null;
function initialize() {
// create the map
var myOptions = {
zoom: 12,
center: new google.maps.LatLng(50.822096, -0.375736),
mapTypeControl: true,
mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU},
navigationControl: true,
mapTypeId: google.maps.MapTypeId.ROADMAP,
scrollwheel:false
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
google.maps.event.addListener(map, 'click', function() {
infowindow.close();
});
// Add markers to the map
// Set up three markers with info windows
// add the points
var point = new google.maps.LatLng(50.810438, -0.374925);
var center = new google.maps.LatLng(50.810438, -0.374925);
var marker = createMarker(point,"Worthing","<p><b>Worthing</b><br>1-13 Buckingham Road,<br>Worthing,<br>West Sussex,<br>BN11 1TH</p>")
var point = new google.maps.LatLng(51.497421,-0.141604);
var center = new google.maps.LatLng(51.497421,-0.141604);
var marker = createMarker(point,"London","<p><b>London</b><br>Portland House,<br>Bressenden Place,<br>London,<br>SW1E 5RS</p>")
var point = new google.maps.LatLng(-33.867487,151.20699);
var center = new google.maps.LatLng(-33.867487,151.20699);
var marker = createMarker(point,"Sydney","<p><b>Sydney</b><br>Level 1, Cosco House,<br>95-101 Sussex Street,<br>Sydney NSW<br>Australia 2000</p>")
// put the assembled side_bar_html contents into the side_bar div
document.getElementById("side_bar").innerHTML = side_bar_html;
$('#side_bar li:first-child').addClass("active");
$('#side_bar li').click(function(){
$('#side_bar li').removeClass("active");
$(this).addClass("active");
});
}
var infowindow = new google.maps.InfoWindow(
{
size: new google.maps.Size(150,50)
});
// This function picks up the click and opens the corresponding info window
function myclick(i) {
google.maps.event.trigger(gmarkers[i], "click");
}
// A function to create the marker and set up the event window function
function createMarker(latlng, name, html) {
var contentString = html;
var iconBase = '../Themes/FreshEgg/assets/img/';
var marker = new google.maps.Marker({
position: latlng,
map: map,
zIndex: Math.round(latlng.lat()*-100000)<<5,
icon: iconBase + 'map_marker_24x46.png',
animation: google.maps.Animation.DROP
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(contentString);
infowindow.open(map,marker);
});
infowindow.setContent(contentString);
infowindow.open(map,marker);
// 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 += '<li><a href="javascript:myclick(' + (gmarkers.length-1) + ')">' + name + '<\/a></li>';
}
google.maps.event.addDomListener(window, 'load', initialize);
HTML:
<ul class="list-inline" id="side_bar"></ul>
<div id="map_canvas"></div>
Add a 4th parameter to your createMarker() function for the default state of markers - createMarker(latlng, name, html, show) - where show will be a boolean variable: true to open on load, false to leave it closed. Then when you call createMarker() in your initialize() method specify true for the marker you want open on load.
Then in createMarker() add a condition that handles this for you - something like:
if (show) {
google.maps.event.trigger(marker, "click");
/*if you're going to take this approach, make sure this is triggered after
*you specify your listener
*alternately, you can also setContent() and open() your infoWindow here
*/
}
To have the map pan to the center when you click on the marker, you first need to disable the auto panning of the map when an infoWindow is open. This can be done where you set the options for your infoWindow:
var infowindow = new google.maps.InfoWindow(
{
size: new google.maps.Size(150,50),
disableAutoPan : true
});
Then, in your listener for the click event on the marker add the function to panTo(LatLng) the position of the marker on your map.
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(contentString);
infowindow.open(map, marker);
map.panTo(marker.getPosition());
});

Show all infowindows open

I'm trying to have custom infowindows float above markers, however I noticed that only one marker can be opened at any one time. Is there a workaround to this?
Here's the code I have produced at the moment:
downloadUrl("AllActivityxml.php", function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var name = markers[i].getAttribute("id");
var address = markers[i].getAttribute("id");
var type = markers[i].getAttribute("venue_type");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng"))
);
var infowindow = new google.maps.InfoWindow();
var html = "<b>" + point + "</b>hello <br/>" + type;
var icon = customIcons[type] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
icon: icon.icon,
shadow: icon.shadow,
zIndex: Math.round(latlng.lat()*-100000)<<5
});
markersArray.push(marker);
bindInfoWindow(marker, map, infoWindow, html);
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(html);
infowindow.open(map,marker);
});
}
});
And when you check this map, notice that I cannot open more than 2 infowindows at once. Why is that?
There is no limitation implicit to the Google Maps API v3 that makes only one InfowWindow available at a time. You need to write your code to do that. If you want an InfoWindow for each marker, make one.
Some thing like (not tested):
function createMarker(latlng, html) {
var contentString = html;
var infowindow = new google.maps.InfoWindow();
var marker = new google.maps.Marker({
position: latlng,
map: map,
zIndex: Math.round(latlng.lat()*-100000)<<5
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(contentString);
infowindow.open(map,marker);
});
}

Google maps infowindow

I am trying to create listeners for some map markers. I can create the markers and they are on the map but, no matter which marker I click on it tells me "Uncaught TypeError: Cannot call method 'open' of undefined" . When I break at the open code it is showing markers[46] which is one more that the highest index. And it doesnt matter which marker I click on its always the same index.
EDIT: I edited the code and pasted all of it. No errors, but nothing happens when I click a marker. I am looking in Chrome and it looks like there isnt a event handler registered
<script>
var map;
var nav = [];
$(document).ready(function () {
//initialise a map
init();
var infowindow = new google.maps.InfoWindow({});
$.get("xxxxxx.kml", function (data) {
html = "";
//loop through placemarks tags
i = 1;
$(data).find("Placemark").each(function (index, value) {
//get coordinates and place name
coords = $(this).find("coordinates").text();
contentString = $(this).find("description").text();
var partsOfStr = coords.split(',');
var lat = parseFloat(partsOfStr[0]);
var lng = parseFloat(partsOfStr[1]);
var myLatLng = new google.maps.LatLng(lng, lat);
place = $(this).find("name").text();
createMarker(myLatLng, place, contentString, i)
//store as JSON
c = coords.split(",")
nav.push({
"place": place,
"lat": c[0],
"lng": c[1]
})
//output as a navigation
html += "<li>" + place + "</li>";
i++;
});
//output as a navigation
$(".navigation").append(html);
//bind clicks on your navigation to scroll to a placemark
$(".navigation li").bind("click", function () {
panToPoint = new google.maps.LatLng(nav[$(this).index()].lng, nav[$(this).index()].lat)
map.panTo(panToPoint);
})
});
markers = [];
function createMarker(myLatLng, title, contentString, i) {
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
title: title
});
google.maps.event.addListener(markers, 'click', function () {
infoWindow.setContent(contentString);
infowindow.open(map, markers[i]);
});
markers[i] = marker;
return marker
}
function init() {
//google.maps.event.addDomListener(window, 'init', Initialize);
var latlng = new google.maps.LatLng(39.047050, -77.131409);
var myOptions = {
zoom: 4,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map"), myOptions);
}
})
This is almost a FAQ. When your loop ends, the value of i is 46 (based on your statement). There is no marker 46, so all the click listeners fail. It can be solved with function closure (a createMarker function which holds the association between the marker and the infowindow contents).
Something like this in your example (not tested), call it from inside your marker creation loop, requires a global markers array, but doesn't require the global infowindow array:
//global markers array
markers = [];
// global infowindow
var infowindow = new google.maps.InfoWindow({});
// createMarker function
function createMarker(myLatLng, title, contentString, i)
{
var marker = new google.maps.Marker({
position: myLatlng ,
map: map,
title:title
});
google.maps.event.addListener(markers, 'click', function() {
infoWindow.setContent(contentString);
infowindow.open(map,markers[i]);
});
markers[i] = marker;
return marker
}

InfoWindow on Marker using MarkerClusterer

This is my html code. I've try anything to add an infowindow on the markers but it don't wanna work. My data is loading from the "Alle_Ortswahlen.page1.xml" file.
Do anyone have an idea how can I add infoWindow to each marker?
<script type="text/javascript">
google.load('maps', '3', {
other_params: 'sensor=false'
});
google.setOnLoadCallback(initialize);
function initialize() {
var stack = [];
var center = new google.maps.LatLng(48.136, 11.586);
var options = {
'zoom': 5,
'center': center,
'mapTypeId': google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"), options);
GDownloadUrl("Alle_Ortswahlen.page1.xml", function(doc) {
var xmlDoc = GXml.parse(doc);
var markers = xmlDoc.documentElement.getElementsByTagName("ROW");
for (var i = 0; i < markers.length; i++) {
// obtain the attribues of each marker
var lat = parseFloat(markers[i].getAttribute("Field4"));
var lng = parseFloat(markers[i].getAttribute("Field6"));
var marker = new google.maps.Marker({
position : new google.maps.LatLng(lat, lng),
map: map,
title:"This is a marker"
});
stack.push(marker);
}
var mc = new MarkerClusterer(map,stack);
});
}
</script>
Before the for cycle, make an empty infowindow object.
var infowindow = new google.maps.InfoWindow();
Than in the for cycle, after the marker, add an event listener, like this:
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent("You might put some content here from your XML");
infowindow.open(map, marker);
}
})(marker, i));
There is some closure magic happening when passing the callback argument to the addListener method. If you are not familiar with it, take a look at here:
Mozilla Dev Center: Working with Closures
So, your code should look something like this:
google.load('maps', '3', {
other_params: 'sensor=false'
});
google.setOnLoadCallback(initialize);
function initialize() {
var stack = [];
var center = new google.maps.LatLng(48.136, 11.586);
var options = {
'zoom': 5,
'center': center,
'mapTypeId': google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"), options);
var infowindow = new google.maps.InfoWindow();
GDownloadUrl("Alle_Ortswahlen.page1.xml", function(doc) {
var xmlDoc = GXml.parse(doc);
var markers = xmlDoc.documentElement.getElementsByTagName("ROW");
for (var i = 0; i < markers.length; i++) {
// obtain the attribues of each marker
var lat = parseFloat(markers[i].getAttribute("Field4"));
var lng = parseFloat(markers[i].getAttribute("Field6"));
var marker = new google.maps.Marker({
position : new google.maps.LatLng(lat, lng),
map: map,
title:"This is a marker"
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent("You might put some content here from your XML");
infowindow.open(map, marker);
}
})(marker, i));
stack.push(marker);
}
var mc = new MarkerClusterer(map,stack);
});
}
So what you need to do is add some code, inside your for-loop, associating an infowindow onclick event handler with each marker. I'm assuming you only want to have 1 infowindow showing at a time, i.e. you click on a marker, the infowindow appears with relevant content. If you then click on another marker, the first infowindow disappears, and a new one reappears attached to the other marker. Rather than having multiple infowindows all visible at the same time.
GDownloadUrl("Alle_Ortswahlen.page1.xml", function(doc) {
var xmlDoc = GXml.parse(doc);
var markers = xmlDoc.documentElement.getElementsByTagName("ROW");
// just create one infowindow without any content in it
var infowindow = new google.maps.InfoWindow({
content: ''
});
for (var i = 0; i < markers.length; i++) {
// obtain the attribues of each marker
var lat = parseFloat(markers[i].getAttribute("Field4"));
var lng = parseFloat(markers[i].getAttribute("Field6"));
var marker = new google.maps.Marker({
position : new google.maps.LatLng(lat, lng),
map: map,
title:"This is a marker"
});
// add an event listener for this marker
google.maps.event.addListener(marker , 'click', function() {
// assuming you have some content in a field called Field123
infowindow.setContent(markers[i].getAttribute("Field123"));
infowindow.open(map, this);
});
stack.push(marker);
}
var mc = new MarkerClusterer(map,stack);
});