Google Maps api v3 - "Infowindow not defined" Error - javascript

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

Related

Google maps LatLngBounds doesn't work sometimes with a javascript object

I have a problem with my map. I'm using the google maps funtion LatLngBounds() in order to calculate the center between two given points.
I'm able to get the location and I consoled.log the value (even if, for some reason the values are empty, I'm still able to print them to the map) so I'm able to place my markers on the map, but for some reason, when I add the function for the bound, I break the map, I get an error and I'm only able to see a marker (one marker.
Here's my code:
var locs;
function initMap() {
var locations_two = [
['<div class=""><p>Vancouver</p></div>', 49.27597, -123.1185, 1],
['<div class=""><p>Ottawa</p></div>', 45.3683, -75.70258]
];
locs = new google.maps.Map(document.getElementById('locs'), {
center: {lat: 49.276873, lng: -123.118948},
zoom: 4
});
var image = $myimage;
var infowindow = new google.maps.InfoWindow();
var marker_two, i;
var bounds = new google.maps.LatLngBounds();
for (i = 0; i < locations_two.length; i++) {
var mybond = locations_two[i];
var myLatLng = new google.maps.LatLng(mybond[1], mybond[2]);
marker_two = new google.maps.Marker({
position: myLatLng,
map: locs,
icon: image
});
bounds.extend(myLatLng);
google.maps.event.addListener(marker_two, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations_two[i][0]);
infowindow.open(map, marker);
}
})(marker_two, i));
map.fitBounds(bounds);
}
}
As I said, I declared the variable var bounds = new google.maps.LatLngBounds(); before the loop and then I use the two other google map function in order to call the map.fitBounds(bounds); at the very end, to center my map but I get this error:
Uncaught (in promise) TypeError: Cannot read property 'fitBounds' of undefined
Which doesn't make sense for me because the bounds variable is actually defined? Any thoughts?
With the posted code I get a javascript error (in Chrome):
Uncaught (in promise) ReferenceError: map is not defined
Your google.maps.Map object is named locs, not map. This line:
map.fitBounds(bounds);
should be:
locs.fitBounds(bounds);
proof of concept fiddle
code snippet:
var locs;
function initMap() {
var locations_two = [
['<div class=""><p>Vancouver</p></div>', 49.27597, -123.1185, 1],
['<div class=""><p>Ottawa</p></div>', 45.3683, -75.70258]
];
locs = new google.maps.Map(document.getElementById('locs'), {
center: {
lat: 49.276873,
lng: -123.118948
},
zoom: 4
});
var infowindow = new google.maps.InfoWindow();
var marker_two, i;
var bounds = new google.maps.LatLngBounds();
for (i = 0; i < locations_two.length; i++) {
var mybond = locations_two[i];
var myLatLng = new google.maps.LatLng(mybond[1], mybond[2]);
marker_two = new google.maps.Marker({
position: myLatLng,
map: locs,
});
bounds.extend(myLatLng);
google.maps.event.addListener(marker_two, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations_two[i][0]);
infowindow.open(map, marker);
}
})(marker_two, i));
locs.fitBounds(bounds);
}
}
html,
body,
#locs {
height: 100%;
margin: 0;
padding: 0;
}
<div id="locs"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap" async defer></script>

Google Maps V3 Javascript: Event listener not being loaded

I don't seem to be able to make Google Maps click event listeners for markers to work. The only detail is that this is being run in a cycle, meaning that in the first time i include the map and run the add markers and their event listeners, the following times I have a function that only adds the markers and the listeners.
This is my initialize function and datasetRealtime is the array of markers:
function initialize() {
var mapOptions = {
zoom: 14,
scaleControl: true,
scaleControlOptions: {
position: google.maps.ControlPosition.TOP_LEFT
},
/* Map Zoom */
center: new google.maps.LatLng(41.186968, -8.697792),
/*Center Coordinate*/
mapTypeId: google.maps.MapTypeId.ROADMAP
}
realtime_map = new google.maps.Map(document.getElementById("map-canvasBig"), mapOptions);
for (var i = 0; i < datasetRealtime.length; i++) {
var latitude = parseFloat(datasetRealtime[i]["latitude"]);
var longitude = parseFloat(datasetRealtime[i]["longitude"]);
var myLatlng = new google.maps.LatLng(latitude, longitude);
var marker = new google.maps.Marker({
position: myLatlng,
map: realtime_map,
title: 'Just some title'
});
google.maps.event.addListener(marker, 'click', function () {
console.log("it worked")
});
}
}
And I am loading it with:
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "http://maps.googleapis.com/maps/api/js?key=mykeygoeshere&sensor=false&callback=initialize";
document.body.appendChild(script);
This is the function that adds the markers and listeners if the map is already loaded:
function addMarkers(){
for (var i = 0; i < datasetRealtime.length; i++) {
var latitude = parseFloat(datasetRealtime[i]["latitude"]);
var longitude = parseFloat(datasetRealtime[i]["longitude"]);
var myLatlng = new google.maps.LatLng(latitude, longitude);
var marker = new google.maps.Marker({
position: myLatlng,
map: realtime_map,
title: 'Just some title'
});
google.maps.event.addListener(marker, 'click', function () {
console.log("it worked")
});
}
}
Update
I am cleaning the markers before I add the new ones with:
function clearOverlays(datasetRealtime) {
for (var i = 0; i < datasetRealtime.length; i++) {
datasetRealtime[i].setMap(null);
}
datasetRealtime = [];
}
I've tried so many ways, even with closures and I don't seem to be able to make it work. The markers are added, but there's no handler when I click on them (the little hand stays wide open)
The proble might be you are rewriting marker at each for loop.
You have to store your markes in a markersArray object.
Your code will look something like this:
var markers = [];
function addMarkers(){
for (var i = 0; i < datasetRealtime.length; i++) {
var latitude = parseFloat(datasetRealtime[i]["latitude"]);
var longitude = parseFloat(datasetRealtime[i]["longitude"]);
var myLatlng = new google.maps.LatLng(latitude, longitude);
var marker = new google.maps.Marker({
position: myLatlng,
map: realtime_map,
title: 'Just some title'
});
google.maps.event.addListener(marker, 'click', function () {
console.log("it worked")
});
markers.push(marker);
}
}
That might work!
May I suggest to you a code refactoring: since you have already an addMarkers method it could be simplier to call it in your initialize method than to rewrite the same code there.
Hi the below code will do for marker click also added a small code.. sry could'nt look into ur code fully still provided info that would help in solving..
var marker = new GMarker(location);
GEvent.addListener(marker, "click", function() {
alert('it works');
});
map.addOverlay(marker);

Google maps v3 array marker

Hy i am unable to display multiple markers in Google Maps V3, i am getting the coordinates correctly but not displays on map. Also no errors in console
map_items[0] = title
map_items[1] = 55.153766, 11.909180
map_items[2] = link
map_items[3] = text
all of them appear correctly if i do an alert.
example
"Title","51.00150763193481, -2.5659284999999272", "link", "text"
function initialize() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 7,
center: new google.maps.LatLng(55.153766, 11.909180),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
for (var x = 0; x < temp.length; x++) {
if(temp[x][1]){
var map_items = temp[x];
var myLatlng = new google.maps.LatLng(map_items[1]);
var marker = new google.maps.Marker({
map: map,
position: myLatlng,
title: map_items[0]
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent('<div class="google_marker">'+map_items[0]+'<br /><p>'+map_items[3]+'</p></div>');
infowindow.open(map, marker);
});
}
}
}
google.maps.LatLng() takes two parameters, not one, so:
var latlon = map_items[1].split(',');
var myLatlng = new google.maps.LatLng(parseFloat(latlon[0]), parseFloat(latlon[1]));
though in fact, it would be better to use objects rather than an array in which each item contains different data types, for example:
marker_data[0] = {
"lat": 55.153766,
"lon": 11.909180,
"title": "My Title",
"link": "http://stackoverflow.com"
}
//etc...
and then you'd access it like this:
var myLatlng = new google.maps.LatLng(marker_data[0].lat, marker_data[0].lon);
Assuming map_items[1] is string
if (temp[x][1]) {
var map_items = temp[x];
var latlng = map_items[1].split(",");
var myLatlng = new google.maps.LatLng(parseFloat(latlng[0]), parseFloat(latlng[1]));
var marker = new google.maps.Marker({
map: map,
position: myLatlng,
title: map_items[0]
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent('<div class="google_marker">' + map_items[0] + '<br /><p>' + map_items[3] + '</p></div>');
infowindow.open(map, marker);
});
}
I think only last map_items would be available when you click on any marker. Creating a different context may solve your problem.
function initialize() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 7,
center: new google.maps.LatLng(55.153766, 11.909180),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
function AttachEventToMarker(marker, map_items){
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent('<div class="google_marker">'+map_items[0]+'<br /><p>'+map_items[3]+'</p></div>');
infowindow.open(map, marker);
});
}
for (var x = 0; x < temp.length; x++) {
if(temp[x][1]){
var map_items = temp[x];
var myLatlng = new google.maps.LatLng(map_items[1]);
var marker = new google.maps.Marker({
map: map,
position: myLatlng,
title: map_items[0]
});
AttachEventToMarker(marker, map_items);
}
}
}

Multiple markers with infowindow

We using multiple marker with infowindow. Everything is working fine.
The issue is when we click marker, the infowindow opens but it doesn't close when click other markers. it stay opened. so can give solutions for this issue.
The code is in http://goo.gl/s0WZx
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 map;
function initialize() {
var mapOptions = {
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: berlin
};
map = new google.maps.Map(document.getElementById("map_canvas"),
mapOptions);
}
function drop() {
for (var i = 0; i < neighborhoods.length; i++) {
setTimeout(function() {
addMarker();
}, i * 200);
}
}
function addMarker() {
var marker = new google.maps.Marker({
position: neighborhoods[iterator],
map: map,
draggable: false
});
markers.push(marker);
var contentString = $("#pop"+iterator).html();
var infowindow = new google.maps.InfoWindow({
content: contentString,
maxWidth: 300,
maxHeight: 500
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map,marker);
});
iterator++;
}
You are creating as much infowindows, as there are markers. In your case,I think one infowindow is enough. So for working with only one infowindow, you could implement this on global scope:
//Using lazy initialization.
//InfoWindow will be created only after the first call
var getInfoWindow = (function(){
var _instance = null;
return function(){
if(_instance == null){
_instance = new google.maps.InfoWindow({
maxWidth: 300,
maxHeight: 500
});
}
return _instance;
};
})();
Also you need to store the contentString for every marker which must be shown on click event. So the final modification of addMarker method will be something like this:
function addMarker() {
var marker = new google.maps.Marker({
position: neighborhoods[iterator],
map: map,
draggable: false
});
markers.push(marker);
//Storing content html
marker.contentString = $("#pop"+iterator).html();
google.maps.event.addListener(marker, 'click', function() {
//Setting content of InfoWindow
getInfoWindow().setContent( marker.contentString );
//Opening
getInfoWindow().open(map,marker);
});
iterator++;
}
Put the var infowindow outside of the addMarker function. Like this:
var infowindow = new google.maps.InfoWindow();
Then inside your addMarker function use
infowindow.setContent(contentString);
This way the infowindow is only created once. Clicking on the different markers just moves the window and sets the content.

GoogleMaps InfoWindow not appearing when Marker is clicked

I have three arrays : myLats, (latitudes) myLngs (longitudes) and myLocs (address strings)
e.g. myLats[0] = 53.3534751, ,myLngs[0] = -2.5682085, myLocs[0] = Longwood Rd Appleton Warrington. So the elements of each array all correspond to each other numerically.
When constructing the map in my initialize() function, I loop through these to place multiple markers at the correct coordinates, and i'm also trying to have each marker having an infowindow appear when clicked, yet when i click a marker an infowindow simply does not appear. Any help with this would be greatly appreciated.
Code:
function initialize() {
var myOptions = {
center: new google.maps.LatLng(54.00366, -2.547855),
zoom: 6,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map_canvas'), myOptions);
var marker, infowindow, i;
for (i = 0; i <= myLats.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(myLats[i], myLngs[i]),
map: map,
clickable: true,
icon: '". url::base() ."resources/icons/accident.png',
});
infowindow = new google.maps.InfoWindow({
content: myLocs[i],
});
google.maps.event.addListener(marker, 'click', function () {
infowindow.open(map, marker);
});
}
}
That's a common problem when dealing with more than one marker. You aren't in fact creating a new window for each marker but must redefining the single window for each marker.
You'll find the problem and solution on page 88 onwards of Google Map API V3
If you are new to Google Maps API, I would recommend reading that book, it gave me a great start and I avoided a lot of the "common" mistakes.
Hope this helps.
Jim
I made a few changes, like adding the markers inside a function, adding 'var', and changing i <= myLats.length to i < myLats.length. It was a combination of these changes that made it work.
var myLats = [ 54.20366, 54.42366, 54.64366];
var myLngs = [ -2.54788, -2.66788, -2.78788];
var myLocs = [ "Loc a" , "Loc b" , "Loc c"];
function initialize()
{
var myOptions =
{
center: new google.maps.LatLng(54.00366,-2.547855),
zoom: 6,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map_canvas'),myOptions);
var marker, infowindow, i;
for (i=0; i < myLats.length; i++)
{
addMarker(i);
}
function addMarker(i) {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(myLats[i],myLngs[i]),
map: map,
clickable: true,
//icon: '". url::base() ."resources/icons/accident.png',
});
var infowindow = new google.maps.InfoWindow({
content: myLocs[i]
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map,marker);
});
}
}
However, I'm guessing you want a solution that keeps only one infowindow open, I had this figured out first:
var myLats = [ 54.20366, 54.42366, 54.64366];
var myLngs = [ -2.54788, -2.66788, -2.78788];
var myLocs = [ "Loc a" , "Loc b" , "Loc c"];
var map, marker, infowindow, i;
function initialize()
{
var myOptions =
{
center: new google.maps.LatLng(54.00366,-2.547855),
zoom: 6,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map_canvas'),myOptions);
infowindow = new google.maps.InfoWindow({ });
for (i = 0; i < myLats.length; i++) {
addMarker(i);
}
}
function addMarker(i) {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(myLats[i],myLngs[i]),
map: map,
clickable: true
//icon: '". url::base() ."resources/icons/accident.png'
});
google.maps.event.addListener(marker, 'click', function(event) {
infowindow.setContent(myLocs[i]);
infowindow.open(map,marker);
});
}

Categories

Resources