google maps v3: how to drop markers, remove, loop again - javascript

I have been studying Google Maps and I would like to accomplish the following goal:
1) drop markers one by one;
2) delete last marker (so just one is in viewport)
3) drop next marker
4) Have info window opened in each marker
5) repeat operation
I have been trying to twist the code for animations AND trying to set map null (setMap(null)), but with no success after calling the drop function. Any suggestion on how to do that?
Bottom line: have something like this. Of course this has one big extra step of difficult, which is pulling data from database.
Here is the code.
Any help will be greatly appreciated.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Marker animations with <code>setTimeout()</code></title>
<style>
#map-canvas{
width:600px;
height:600px;
position: "absolute";
top: 0px;
left: 0px;
overflow: "hidden";
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script>
var berlin = new google.maps.LatLng(52.520816, 13.410186);
var neighborhoods = [
new google.maps.LatLng(52.511467, 13.447179),
new google.maps.LatLng(52.549061, 13.422975),
new google.maps.LatLng(52.497622, 13.396110),
new google.maps.LatLng(52.517683, 13.394393)
];
var markers = [];
var iterator = 0;
var Marker;
var map;
function initialize() {
var mapOptions = {
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: berlin
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
drop();
}
function drop(){
for (var i = 0; i < neighborhoods.length; i++) {
var m = neighborhoods[i];
(function(n){
setTimeout(function() {
addMarker(n);
}, i * 500);
}(m));
}
}
function addMarker() {
markers.push(new google.maps.Marker({
position: neighborhoods[iterator],
map: map,
draggable: false,
animation: google.maps.Animation.DROP
}));
iterator++;
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas"></div>
</body>
</html
>

Did you want only one marker to display at a time?
Here is some code that does that:
$(function() {
var BERLIN = new google.maps.LatLng(52.520816, 13.410186);
var NEIGBORHOODS = [
new google.maps.LatLng(52.511467, 13.447179),
new google.maps.LatLng(52.549061, 13.422975),
new google.maps.LatLng(52.497622, 13.396110),
new google.maps.LatLng(52.517683, 13.394393)];
var map = null;
var marker = null;
var index = 0;
var infoWindow = null;
function createMap() {
return new google.maps.Map(document.getElementById('map-canvas'), {
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: BERLIN,
zoom: 12
});
}
function dropMarker(map, pos) {
return new google.maps.Marker({
map: map,
position: pos,
draggable: false,
animation: google.maps.Animation.DROP
});
}
function changeMarker() {
if (marker) {
infoWindow.close();
marker.setMap(null);
}
var pos = NEIGBORHOODS[index];
marker = dropMarker(map, pos);
infoWindow.setContent('lat: ' + pos.lat() + '<br />' + 'lng: ' + pos.lng());
setTimeout(function () {
infoWindow.open(map, marker);
}, 500);
index = (index + 1) % NEIGBORHOODS.length;
setTimeout(function () {
changeMarker();
}, 2000);
}
map = createMap();
infoWindow = new google.maps.InfoWindow()
changeMarker();
});
Notice how the changeMarker() function does its work, then usessetTimeout() to call itself again. This sets up an infinite loop where changeMarker() is called every two seconds.
I used setTimeout() to delay the showing of the Info Window by a half second so it does not appear until the drop is finished.
jsfiddle demo

Related

How to Check Current Time with Restaurant Times on Google Maps API

I'm looking for a way to check the current local time with the restaurant's opening and closing time. I'm using Google Maps API and I have been able to show some restaurants on the map. The map centre is Adelaide, Australia, but the tool asks for the user location and goes there. I want to compare the time and if the time is not in between, the restaurant should not be on the map. Also, if the hours are not set for a restaurant, then the tool should display the restaurant all the time.
Here is the CSS and JavaScript code. I have removed the API key.
<div id="map"></div>
<script>
var infoWindow;
var gmarkers = [];
var map;
function initMap() {
infoWindow = new google.maps.InfoWindow();
map = new google.maps.Map(document.getElementById('map'), {
zoom: 13,
center: {lat: -34.9285,lng: 138.6007}
});
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
initialLocation = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
map.setCenter(initialLocation);
});
}
var markers = [
// A
{coords:{lat:-34.92366, lng:138.567063}, content:'<p><strong>Abyssinian Restaurant</strong></p>', timing: {open: 1200, close: 1400}},
// B
{coords:{lat:-34.923885, lng:138.562042}, content:'<p><strong>British Raj</strong></p>', timing: {open: 0800, close: 1700}},
{coords:{lat:-34.843645, lng:138.507653}, content:'<p><strong>Banyan Hotel Port Adelaide</strong></p>', timing: {open: 0900, close: 1900}},
];
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < markers.length; i++) {
gmarkers.push(addMarker(markers[i]));
bounds.extend(markers[i].coords);
}
// map.fitBounds(bounds);
function addMarker(props) {
var currentDate = new Date();
var marker = new google.maps.Marker({
position: props.coords,
map: map,
icon:'Ellipse 1.png'});
if (props.content){
marker.addListener('click', function(){
infoWindow.setContent(props.content);
infoWindow.open(map,marker);});
}
return marker;
}
}
</script>
<script src="markerclusterer.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?key=API_KEY&callback=initMap" async defer></script>
CSS
<style>
#charset "utf-8";
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 80%;
}
/* Optional: Makes the sample page fill the window. */
html, body {
height: 100%;
margin: 0;
padding: 0;
}
</style>
Try modifying your code as follows:
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < markers.length; i++) {
const marker = addMarker(markers[i]);
if (marker) {
gmarkers.push(marker);
bounds.extend(markers[i].coords);
}
}
// map.fitBounds(bounds);
function addMarker(props) {
var currentDate = new Date();
const currentTime = parseInt(currentDate.getHours().toString() + currentDate.getMinutes().toString());
if (props.timing.open > currentTime || props.timing.close < currentTime) {
return false;
}
var marker = new google.maps.Marker({
position: props.coords,
map: map,
icon:'Ellipse 1.png'
});
if (props.content) {
marker.addListener('click', function() {
infoWindow.setContent(props.content);
infoWindow.open(map, marker);
});
}
return marker;
}
My local time is 919 (09:19 AM) so only "Banyan Hotel Port Adelaide" and "British Raj" show up on the map, because "Abyssinian Restaurant" opens at 1200 (12:00 PM).
Hope this helps!

how to refresh maps with ajax request?

I want to reload map in ajax call.This code is reloading whole page when i change status it reloads whole page.I want after 10 seconds only map reloads not whole page. if i select on change available then map reloads after every 10 seconds in available option.
i have drivers if i select status of driver available then map shows the drivers which are available. i want to refresh map after 10 sec so that i can see if there is any other driver available. if available then it will show on map without reloading whole page. This is what i want.
i am refreshing content in some div of the page by using jQuery load() function but its not working.
Html:
<div class="row">
<div class="col-md-12">
<div id="map" style="height: 550px;">
<div id="time">
<?php echo date('H:i:s');?>
</div>
</div>
</div>
</div>
Script:
$('#status').change(function () {
var job_status = $(this).val();
$.ajax({
url: '{{ URL::to('/get_drivers/')}}' + '/' + $(this).val(),
type: 'get',
datatype: 'json',
success: function (response) {
setInterval("my_function();", 10000);
function my_function() {
$('#map').load(location.href + ' #time');
}
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 10,
center: {lat: 31.5204, lng: 74.3587},
mapTypeId: 'roadmap'
});
var infowindow = new google.maps.InfoWindow({});
var marker, i;
{{--var carIcon = '{{asset('images/red-car.png')}}';--}}
if (gmarkers.length > 0) {
for (i = 0; i < gmarkers.length; i++) {
if (gmarkers[i].getMap() != null) {
gmarkers[i].setMap(null);
} else {
gmarkers[i].getMap();
gmarkers[i].setMap(map);
}
}
gmarkers = [];
}
for (i = 0; i < locationData.length; i++) {
if (job_status == 8) {
if (job_status === '') {
gmarkers = [];
}
else {
for (i = 0; i < locationData2.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locationData2[i]['driver_lat'], locationData2[i]['driver_long']),
map: map,
optimized: false,
icon: '{{asset('images/grey-car.png')}}'
});
google.maps.event.addListener(marker, 'mouseover', (function (marker, i) {
return function () {
infowindow.setContent('<h6><b>' + locationData2[i]['first_name'] + '</h6>');
infowindow.open(map, marker);
}
})(marker, i));
google.maps.event.addListener(map, 'click', (function (marker, i) {
return function () {
infowindow.setContent();
infowindow.close(marker);
}
})(marker, i));
// Push your newly created marker into the array:
gmarkers.push(marker);
var myoverlay = new google.maps.OverlayView();
myoverlay.draw = function () {
// add an id to the layer that includes all the markers so you can use it in CSS
this.getPanes().markerLayer.id = 'markerLayer';
};
myoverlay.setMap(map);
}
}
}
});
You do not need to renew the whole map but drivers markers only (or to be even more precise - not whole markers but their positions only)
I use google own example and put there couple of markers which positions get renewed to random location every second.
//random locations
var latArr = [-20.363882, -21.363882, -22.363882, -23.363882, -24.363882, -25.363882, -26.363882, -27.363882, -28.363882, -29.363882];
var lngArr = [125.044922, 126.044922, 127.044922, 128.044922, 129.044922, 130.044922, 131.044922, 132.044922, 133.044922, 134.044922];
//global array to hold all markers
var markersArr = [];
//map init from google example
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: {lat: -25.363882, lng: 131.044922}
});
//create markers
var marker1 = new google.maps.Marker({
position: map.getCenter(),
icon: {
path: google.maps.SymbolPath.CIRCLE,
scale: 10
},
draggable: true,
map: map
});
var marker2 = new google.maps.Marker({
position: map.getCenter(),
icon: {
path: google.maps.SymbolPath.BACKWARD_CLOSED_ARROW,
scale: 5
},
draggable: true,
map: map
});
markersArr.push(marker1);
markersArr.push(marker2);
}
//function to change markers locations
function renewMarkers(){
for(i=0; i<markersArr.length; i++){
var lt = Math.floor(Math.random()*10);
var ln = Math.floor(Math.random()*10);
markersArr[i].setPosition({lat: latArr[lt], lng: lngArr[ln]})
}
}
setInterval(renewMarkers, 1000);
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html, body {
height: 100%;
margin: 0;
padding: 0;
}
<!-- Replace the value of the key parameter with your own API key. -->
<script async defer
src="https://maps.googleapis.com/maps/api/js?callback=initMap">
</script>
<div id="map"></div>

Directions to/from here infowindow in Maps API

I'm trying to replicate similar functionality in Google Maps where you right click & it gives an option to have directions to/from that point. The struggle I'm having is interacting with the infowindow & passing the lat/longs back.
The listener creates the infowindow fine. but I can;t work out how to pass the lat/longs back into the javascript (either as an origin or destination) so as I can then use it in the directions service. I'll eventually have a second marker which will populate the other value in origin/destination. Once the array has two values I'll call the directions service.
All the examples I've seen have required some form of manual input to define the second part of the address.
I'm still very new to this, so please go easy on me; I've tried my best to provide the most trimmed down sample code to demonstrate my issue.
var mapCanvas = "map-canvas",
map,
infowindow = new google.maps.InfoWindow(),
LocationArr = [],
o;
google.maps.event.addDomListener(window, "load", function(){
map = new google.maps.Map(document.getElementById(mapCanvas), {zoom: 13,center: {lat: 53.4723272,lng: -2.2935022}});
var geocoder = new google.maps.Geocoder;
google.maps.event.addListener(map, "click", function(o) {
LocationArr.push(o.latLng);
var a = new google.maps.Marker({
position: o.latLng,
map: map,
});
var content = "<input type='button' name='DirFrom' value='Directions from here' onclick='DirFromHere()' id='Dir_From'>"
+ "<input type='button' name='DirTo' value='Directions to here' onclick='DirToHere()' id='Dir_To'>"
infowindow.setContent(content);
infowindow.open(map, a);
});
});
function DirFromHere(LocationArr){
console.log(LocationArr.length);
}
function DirToHere(LocationArr){
LocationArr=[];
}
html, body {
height: 100%;
width: 100%;
}
#map-canvas {
position: absolute;
top: 0%;
left: 0%;
width: 100%;
height: 100%;
}
<html>
<head>
<link href="css/styles.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="map-canvas"></div>
<script src="https://maps.googleapis.com/maps/api/js?libraries=places"></script>
<script src="js/aqrouting.js"></script>
</body>
</html>
Here is a simple example of how you can do that, using vanilla Javascript only. Code is commented. That should be enough to understand how it works.
var directionDisplay;
var directionsService = new google.maps.DirectionsService();
var map, infowindow;
var start, end, pos;
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer();
// Map options
var center = new google.maps.LatLng(45.07, 7.67);
var myOptions = {
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: center
}
// Create map
map = new google.maps.Map(document.getElementById("map-canvas"), myOptions);
directionsDisplay.setMap(map);
// Create infowindow
infowindow = new google.maps.InfoWindow({
content: '',
map: map
});
// Listen for map click
google.maps.event.addListener(map, 'click', function(e) {
// Save current position
pos = e.latLng;
// Set infowindow position and open
infowindow.setPosition(pos);
infowindow.open(map)
});
// Create infowindow buttons
let btnFrom = document.createElement("button");
btnFrom.id = 'directionsFrom';
btnFrom.innerHTML = 'Directions from here'
let btnTo = document.createElement("button");
btnTo.id = 'directionsTo';
btnTo.innerHTML = 'Directions to here'
// Add DOM listener to DIRECTIONS FROM button
google.maps.event.addDomListener(btnFrom, 'click', function() {
// Set start position
start = pos;
});
// Add DOM listener to DIRECTIONS TO button
google.maps.event.addDomListener(btnTo, 'click', function() {
// Set end position
end = pos;
// Check that start and end position both are an instance of LatLng
if ((start instanceof google.maps.LatLng) && (end instanceof google.maps.LatLng)) {
// We have a start and end position so we can request directions
getDirections();
}
});
// Add the 2 buttons in a DIV
let contentDiv = document.createElement('div');
contentDiv.appendChild(btnFrom);
contentDiv.appendChild(btnTo);
// Add the DIV as the infowindow content
infowindow.setContent(contentDiv);
}
// Make a Directions request and display it on the map
function getDirections() {
var method = 'DRIVING';
var request = {
origin: start,
destination: end,
travelMode: google.maps.DirectionsTravelMode[method]
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
// Close infowindow
infowindow.close();
}
});
}
initialize();
#map-canvas {
height: 150px;
}
<div id="map-canvas"></div>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk
"></script>

Debug my Google map Cluster Code

I am using this code to create a Google map with 3 points that are hidden within one and when the one marker is clicked thepoints either get merged into the one or they open up into 3 separate ones, however the map is not appearing can any one examine my code and see the potential problem?
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>favorite cities</title>
<style>
html, body, #map-canvas {
height: 100%;
margin: 0px;
padding: 0px
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script>
<script>
(function() {
window.onload = function(){
var options = {
zoom: 3,
center: new google.maps.LatLng(37.99, -93.77),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map'), options);
var mgr = new MarkerManager(map);
var A = new google.maps.Marker({
position: new google.maps.LatLng(37.99, -93.77),
icon: 'img/cluster.png'
});
google.maps.event.addListener(A, 'click', function() {
map.setZoom(7);
map.setCenter(Kloof.getPosition());
});
var Cities = [A];
var Schools = [
//SChool1
new google.maps.Marker({position: new google.maps.LatLng(38.99, -93.97)}),
//School2
new google.maps.Marker({position: new google.maps.LatLng(37.89, -94.77)}),
//School3
new google.maps.Marker({position: new google.maps.LatLng(37.79, -95.77)})
];
google.maps.event.addListener(mgr, 'loaded', function() {
agr.addMarkers(Cities, 11, 6);
agr.addMarkers(Schools, 6);
agr.refresh
});
};
})();
</script>
</head>
<body>
<div id="map-canvas"></div>
</body>
</html>
Change:
var map = new google.maps.Map(document.getElementById('map'), options);
To:
var map = new google.maps.Map(document.getElementById('map-canvas'), options);
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>favorite cities</title>
<style>
html, body, #map-canvas {
height: 100%;
margin: 0px;
padding: 0px
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script>
<script>
(function() {
window.onload = function(){
var options = {
zoom: 3,
center: new google.maps.LatLng(37.99, -93.77),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map-canvas'), options);
var mgr = new MarkerManager(map);
var A = new google.maps.Marker({
position: new google.maps.LatLng(37.99, -93.77),
icon: 'img/cluster.png'
});
google.maps.event.addListener(A, 'click', function() {
map.setZoom(7);
map.setCenter(Kloof.getPosition());
});
var Cities = [A];
var Schools = [
//SChool1
new google.maps.Marker({position: new google.maps.LatLng(38.99, -93.97)}),
//School2
new google.maps.Marker({position: new google.maps.LatLng(37.89, -94.77)}),
//School3
new google.maps.Marker({position: new google.maps.LatLng(37.79, -95.77)})
];
google.maps.event.addListener(mgr, 'loaded', function() {
agr.addMarkers(Cities, 11, 6);
agr.addMarkers(Schools, 6);
agr.refresh
});
};
})();
</script>
</head>
<body>
<div id="map-canvas"></div>
</body>
</html>
I changed the code to the following:
<
var schoolArray = []; //Global array to store the POINTS
var SchoolPoints = [[-29.788911, 30.852721, 'Thomas More College'], //I am creating a global array to store the MARKERS
[-29.781297, 30.838465, 'Kloof Senior Primary School'],
[-29.827008, 30.881706, 'Pinetown Boys HighSchool']];
function initialize() { //I am initializing the google map and how it will appear on my dashboard
var myOptions = {
zoom: 9,
center: new google.maps.LatLng(-29.807762, 30.854261),
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var mcOptions = { //this is where i determine BY GRID the amount of tiles that will determine if my schools points cluster or if they are separate and also the max zoom level the individual points are visual at
gridSize: 25,
maxZoom: 20
};
var mc = new MarkerClusterer(map, [], mcOptions); //this creates the blue cluster you see initially on the map
google.maps.event.addListener(map, 'click', function() { //upon click the map zooms in and displays the 3 schools with separate markers
infowindow.close();
});
// This is where the markers are added to the map and sorted into the cluster
for(var i=0; i<SchoolPoints.length; i++){ //This is where where i am setting up my markers on the map based off the number of elements within the points array
createMarker(new google.maps.LatLng(SchoolPoints[i][0], SchoolPoints[i][1]), SchoolPoints[i][2]);
}
mc.addMarkers(schoolArray , true); //now the markers are clustered together in the blue symbol
}
var infowindow = new google.maps.InfoWindow({ //I am determining the size of the info window that will be displayed by my school points
size: new google.maps.Size(500, 250)
});
function createMarker(latlng, html) { //this function is where i create the individual markers
var contentString = html;
var marker = new google.maps.Marker({
position: latlng,
map: map,
icon: '',
});
marker.setAnimation(google.maps.Animation.DROP); //I decided for aesthetic reasons i would like to see if i could animate the markers and so i added a drop animation
google.maps.event.addListener(marker, 'click', function() { //when clicking the markers their info windows are displayed
infowindow.setContent(contentString); //This sets the info window to have the content listed in the array visible
infowindow.open(map, marker);
});
schoolArray.push(marker);
}
window.onload = initialize;
​

Google Maps api v3 - "Infowindow not defined" Error

The map comes up and the point appears. I have the title appearing as well. But as soon as I click on the marker to get info, nothing appears. Firebug info is below.
The information is being brought in via a database and there are multiple items; multiple markers are shown on the map as they should.
Any help would be apprecaited. Thanks..
Firebug Point Info:
MarkLat[i] = xx.xxxxxxxxxxxxxx;
MarkLong[i] = -xx.xxxxxxxxxxxxxx;
MarkerTitle[i] = 'Title 1';
Display[i] = '<table><tr><td>Title 1</td></tr><tr><td>Title 1 Address<br />Title 1 City, State Zip</td></tr><tr><td>Title 1 Phone</td></tr><tr><td>Title 1 Email</td></tr><tr><td>Title 1 URL</td></tr></table>';
Firebug Error:
infowindow is not defined
infowindow.open(map,marker);
Code:
<script type="text/javascript">
var i = -1;
var MarkLat=new Array();
var MarkLong=new Array();
var MarkerTitle=new Array();
var Display=new Array();
var MapCenter = new google.maps.LatLng(xx.xxxxxxxxxxxxxx,-xx.xxxxxxxxxxxxxx)
</script>
<script type="text/javascript">
var i = i + 1;
MarkLat[i] = [[Lat]];
MarkLong[i] = [[Long]];
MarkerTitle[i] = '[[Title]]';
Display[i] = '<table><tr><td>[[Title]]</td></tr><tr><td>[[Address]]<br />[[City]], [[State]] [[Zip]]</td></tr><tr><td>[[Phone]]</td></tr><tr><td>[[Email]]</td></tr><tr><td>[[WebURL]]</td></tr></table>';
</script>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
function initialize() {
var myOptions = {
zoom: 12,
center: MapCenter,
zoomControl: true,
zoomControlOptions: {
position: google.maps.ControlPosition.TOP_RIGHT,
style: google.maps.ZoomControlStyle.SMALL
},
mapTypeControl: true,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
},
scaleControl: true,
scaleControlOptions: {
position: google.maps.ControlPosition.TOP_CENTER
},
mapTypeId: google.maps.MapTypeId.ROADMAP,
};
var map = new google.maps.Map(document.getElementById('map_canvas'),myOptions);
for (var i = 0, length = 50; i < length; i++) {
var latLng = new google.maps.LatLng(MarkLat[i],MarkLong[i]);
var infoWindow = new google.maps.InfoWindow(Display[i]);
// Creating a marker and putting it on the map
var marker = new google.maps.Marker({
position: latLng,
map: map,
title: MarkerTitle[i]
});
google.maps.event.addDomListener(marker, 'click', function() {
infowindow.open(map,marker);
});
}
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
Changing to a capital W was not enough for me. Only one location was being opened. I tested your code with two points:
MarkLat = [];
MarkLong = [];
Display = [];
MarkerTitle= [];
MarkLat[0] = 0;
MarkLong[0] = 0;
Display[0] = { content: "hi" };
MarkerTitle[0] = "hello";
MarkLat[1] = 10;
MarkLong[1] = 10;
Display[1] = { content: "hi 2" };
MarkerTitle[1] = "hello 2";
I'm guessing you only want one InfoWindow on the screen at any given time. Then, a single InfoWindow should be declared, with the contents kept inside the marker, and have the contents change as the marker is clicked.
var infoWindow = new google.maps.InfoWindow();
for (var i = 0, length = Display.length; i < length; i++) {
var latLng = new google.maps.LatLng(MarkLat[i],MarkLong[i]);
// Creating a marker and putting it on the map
var marker = new google.maps.Marker({
position: latLng,
map: map,
title: MarkerTitle[i],
infoWindowContent: Display[i]
});
// Notice I used the 'this' keyword inside the listener
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(this.infoWindowContent.content);
infoWindow.open(map,this);
});
}
The alternative, having many InfoWindows pop up, needs a change to click listener, so that a reference to each individual InfoWindow is preserved. This effect is accomplished with an anonymous function wrapped around the infoWindow.open function (a new function scope is created).
for (var i = 0, length = Display.length; i < length; i++) {
var latLng = new google.maps.LatLng(MarkLat[i],MarkLong[i]);
var infoWindow = new google.maps.InfoWindow(Display[i]);
// Creating a marker and putting it on the map
var marker = new google.maps.Marker({
position: latLng,
map: map,
title: MarkerTitle[i]
});
google.maps.event.addListener(marker, 'click', (function(infoWindow) {
return function() {
infoWindow.open(map,this);
}
})(infoWindow));
}
infowindow != infoWindow
You just have declared it with a capital, trying to use it without

Categories

Resources