Infowindow on google map is not working - javascript

I am using google map api v3 with js and I am trying to to open infowndow on each marker on the map but through my code it is not opening here is my code sample please check it and tell me where is the error
<script type="text/javascript">
var map;
var markers = new Array();
function initialize() {
var map_center = new google.maps.LatLng(31.2330555556,72.3330555556);
var GPS = <%=GPS %>
var myOptions = {
zoom: 8,
scaleControl:true,
pancontrol: true,
streetViewControl: true,
center: map_center,
mapTypeControl: true,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
},
mapTypeId: google.maps.MapTypeId.HYBRID
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var infowindow = new google.maps.InfoWindow();
for(i=0; i<GPS.length; i++)
{
var image = 'ico/no.png';
var ContentString = GPS[i].TITLE;
markers[i] = new google.maps.Marker(
{
position: GPS[i].GPS,
map: map,
draggable:true,
icon:image,
title:GPS[i].TITLE
});
google.maps.event.addListener(markers[i], 'click', function() {
infowindow.setContent(ContentString);
infowindow.open(map,markers[i]);
});
}
}
</script>

Try the following code:
google.maps.event.addListener(markers[i], 'click', function() {
infowindow.setContent(ContentString);
infowindow.open(map,this);
});

I have completed a program recently using the same api as yours. Facing to the same problem,I found the key factor is that the function of addlistener would work after the loop ended.It is said that the variable 'i' has reach to the maximizing value when the function of addlistener worked.So I have added a few steps to handle the problem. You can have a look at mine and I hope it is helpful for you.
function ShowParkingPoints() {
var adNum=document.getElementById("tableOne").rows.length;
var i;
var j;
var l;
var ly;
for (i=1;i<adNum;i++)
{
for(j=1;j<5;j++)
{
var k=i-1;
addArray[k]+=document.getElementById("tableOne").rows[i].cells[j].innerHTML;
}
}
for (i=0;i<adNum-1;i++){
var image = new sogou.maps.MarkerImage('images/flag.png',
new sogou.maps.Size(60, 60),
new sogou.maps.Point(0,0),
new sogou.maps.Point(0, 60));
var shape = {
coord: [1, 1, 1, 20, 18, 20, 18 , 1],
type: 'poly'
};
geocoder.geocode( { 'address': addArray[i]}, function(results, status) {
if (status == sogou.maps.GeocoderStatus.OK) {
var str=results[0].formatted_address;
//infowindow.setContent(str);
var marker1= new sogou.maps.Marker({
map: map,
icon: image,
shape: shape,
draggable:true,
position: results[0].geometry.location
});
i=i-1
markerArrayS[i]=marker1;
locationArray[i]=results[0].geometry.location;
sogou.maps.event.addListener(markerArrayS[i], 'click', function(event) {
makerClicked(event.latLng);
});
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
map.setCenter(mapCenter);
map.setZoom(13);
}

I think you just need to use 'i=i-1' to replace 'i' when you start to login event watcher.You can have a try. In a way,you need to notice that the order you storage in arrays when you want to read them out.

Related

Googlemaps API loads slow with many markers

Im trying to load around 600 googlemap markers on page load using the function addMarker.
The page takes a lot of time to load.
Is there anything I can do to make it load faster while keep using the addMarker function?
Thanks.
var map
var myLatlng = new google.maps.LatLng(35.9531719,14.3712201);
var markerBounds = new google.maps.LatLngBounds();
var markers = {};
function HomeControl(controlDiv, map)
{
google.maps.event.addDomListener(zoomout, "click", function() {
var currentZoomLevel = map.getZoom();
if(currentZoomLevel != 0)
{
map.setZoom(currentZoomLevel - 1);
}
});
google.maps.event.addDomListener(zoomin, "click", function() {
var currentZoomLevel = map.getZoom();
if(currentZoomLevel != 21)
{
map.setZoom(currentZoomLevel + 1);
}
});
}
function initialize()
{
var googleMapOptions = {
center: new google.maps.LatLng(35.9531719,14.3712201),
zoom: 11,
mapTypeId: google.maps.MapTypeId.ROADMAP,
zoomControl: false,
streetViewControl: false,
panControl: false,
draggable: true
};
map = new google.maps.Map(document.getElementById("map-canvas"), googleMapOptions);
google.maps.event.addListener(map, "idle", function() {
addMarker(latitude,longitude,id,'Title','url');
});
var homeControlDiv = document.createElement("div");
var homeControl = new HomeControl(homeControlDiv, map);
}
var infowindow = new google.maps.InfoWindow({
content: ""
});
function addMarker(lat,long,id,desc,url)
{
var myIcon = new google.maps.MarkerImage("/images/pips/"+id+".png", null, null, null, new google.maps.Size(28,38));
var myLatlng = new google.maps.LatLng(lat,long);
var marker = new google.maps.Marker({
map: map,
title: desc,
position: myLatlng,
icon: myIcon,
id: id
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent('' + desc + '');
infowindow.setPosition(marker.getPosition());
infowindow.open(map, marker);
});
markers[id] = marker;
markerBounds.extend(myLatlng);
google.maps.event.addListener(marker, "click", function() {
infowindow.open(map,marker);
});
}
google.maps.event.addDomListener(window, "load", initialize);
</script>
You can use clustering, it joins neighbor markers into one, and expand only on zoom
You can do clustering in client side, as well as server side, depending the amount of markers...
I would suggest to use server clustering if amount is more than 4000, otherwise client should look fine

Setting the content for each marker Google Maps

Need a quick help with setting up the content for each marker that I'm creating
I'm looping through my Locations Obj that holds Lat,Lng for each marker (locationObj),
the content for each marker is been hold by other obejct (PermutationObj).
example:
locationObj-- > {"Lat":"34.163291","Lng":"-118.685123"} etc....
PermutationObj -- > ElectronicPopContent,LocationName
The thing is I'm getting for all the markers that I'm displaying on the map the first content and location name from the PermutationObj.
How can I fix it???
JS Code:
var locationObj;
var PermutationObj;
var map;
var mapOptions;
var shape = {
coord: [1, 1, 1, 20, 18, 20, 18, 1],
type: 'poly'
};
function setMap(locationList, permutation) {
// List of Lat,Lng
locationObj = $.parseJSON(locationList);
PermutationObj = $.parseJSON(permutation);
var qMapTypeId = google.maps.MapTypeId.SATELLITE
var LatLngCenter = new google.maps.LatLng(34.163291, -118.685123);
var mapOptions = {
zoom: 4,
center: LatLngCenter,
mapTypeControl: true,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
}
}
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
var bounds = new google.maps.LatLngBounds();
for (i in locationObj) {
var LatLngPair = new google.maps.LatLng(locationObj[i]["Lat"], locationObj[i]["Lng"]);
bounds.extend(LatLngPair);
map.fitBounds(bounds);
// for (j in PermutationObj) {
// // var image = PropObj[j]["ElectroincImageURL"];
// var content = PermutationObj[j]["ElectronicPopContent"];
// break
// }
var content = PermutationObj[i]["ElectronicPopContent"];
marker = new google.maps.Marker({
position: LatLngPair,
map: map,
draggable: false,
// icon: image,
shape: shape,
anchorPoint: new google.maps.Point(12, -25)
});
//Setting up the content of the info window dynamic wise.
var infowindow = new google.maps.InfoWindow({
content: content
});
//Setting up an event listener, When the user clicks the marker, an info window opens.
google.maps.event.addListener(marker, 'click', function () {
infowindow.setContent(content);
infowindow.open(map, marker);
});
}
}
Changed a few things, the first is having only one instance of the InfoWindow, the other is storing the content as a marker property and use it on the click, the last is having an instance per marker by using var marker = ... instead of marker = ... Let me know if this works for you.
var locationObj;
var PermutationObj;
var map;
var mapOptions;
var infowindow = new google.maps.InfoWindow({ });
var shape = {
coord: [1, 1, 1, 20, 18, 20, 18, 1],
type: 'poly'
};
function setMap(locationList, permutation) {
// List of Lat,Lng
locationObj = $.parseJSON(locationList);
PermutationObj = $.parseJSON(permutation);
var qMapTypeId = google.maps.MapTypeId.SATELLITE
var LatLngCenter = new google.maps.LatLng(34.163291, -118.685123);
var mapOptions = {
zoom: 4,
center: LatLngCenter,
mapTypeControl: true,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
}
}
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
var bounds = new google.maps.LatLngBounds();
for (i in locationObj) {
var LatLngPair = new google.maps.LatLng(locationObj[i]["Lat"], locationObj[i]["Lng"]);
//Are you sure you need these 2 lines here?
bounds.extend(LatLngPair);
map.fitBounds(bounds);
var marker = new google.maps.Marker({
position: LatLngPair,
map: map,
draggable: false,
shape: shape,
anchorPoint: new google.maps.Point(12, -25),
infoWindowContent: PermutationObj[i]["ElectronicPopContent"]
});
//Setting up an event listener, When the user clicks the marker, an info window opens.
google.maps.event.addListener(marker, 'click', function () {
infowindow.setContent(marker.infoWindowContent);
infowindow.open(map, marker);
});
}
}

How to define custom size on Google Map when using closures in event listeners

I' am using Google Map to plot the marker and a small popup box that will appear when someone clicks on the market. Image is attached. By Default, Google has set fixed width of the Popup and I wanted to change its size. I was not able to anything on Documentation.
Below are my codes
<script type="text/javascript">
function initialize() {
var mapOptions = {
zoom: 5,
center: new google.maps.LatLng(-14.306407, -170.695018),
mapTypeId: google.maps.MapTypeId.TERRAIN
};
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
var voyagePlanCoordinates = [
new google.maps.LatLng(),
];
var voyagePath<?php echo $voyage_id; ?> = new google.maps.Polyline({
path: voyagePlanCoordinates,
geodesic: true,
strokeColor: "",
strokeOpacity: 1.0,
strokeWeight: 5
});
voyagePath.setMap(map);
setMarkers(map, voyages);
}
var voyages = [];
function setMarkers(map, locations) {
var image = {
url: '/wp-content/themes/theme/resources/images/marker.png',
size: new google.maps.Size(20, 32),
origin: new google.maps.Point(0,0),
anchor: new google.maps.Point(0, 32)
};
for (var i = 0; i < locations.length; i++) {
var voyage = locations[i];
var myLatLng = new google.maps.LatLng(voyage[1], voyage[2]);
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
icon: image,
title: voyage[0],
zIndex: voyage[3]
});
voyage_msg(marker, i);
}
}
function voyage_msg(marker, num){
var message = [];
var infowindow = new google.maps.InfoWindow({
content: message[num]
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(marker.get('map'), marker);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
Please Help!
You don't need any extra code or api call to set the width of the popover. All you need is basic CSS
.map-closures{
width: 200px;
}
That should do the trick.

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

Google Maps API v3 - Markers All Share The Same InfoWindow

I've been digging around everywhere and I can't seem to figure this out. It's driving me crazy! I'm a newbie to javascript in general, so I can't quite put a finger on the translation that would fix my issue. I noticed that a lot of people have this problem, but they all seem to use more advanced(or just confusing) code than I. Anyway, here goes!
I've been having the problem where all of my markers share the same content.
function initialize() {
var myOptions = {
center: new google.maps.LatLng(34.151271, -118.449537),
zoom: 9,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: false,
streetViewControl: false,
panControl: false,
zoomControl: true,
zoomControlOptions: { style: google.maps.ZoomControlStyle.SMALL },
};
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
setMarkers(map, clubs);
}
var clubs = [
['Poop', 34.223868, -118.601575, 'Dookie'],
['Test Poop', 34.151271, -118.449537, 'Test Business']
];
function setMarkers(map, locations) {
var image = new google.maps.MarkerImage('images/image.png',
new google.maps.Size(25, 32),
new google.maps.Point(0,0),
new google.maps.Point(0, 32)
);
var shape = {
coord: [1, 1, 1, 20, 18, 20, 18 , 1],
type: 'poly'
};
for (var i = 0; i < locations.length; i++) {
var club = locations[i];
var myLatLng = new google.maps.LatLng(club[1], club[2]);
var infowindow = new google.maps.InfoWindow();
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
icon: image,
shape: shape,
title: club[0],
});
google.maps.event.addListener(marker, 'click', function(){
infowindow.setContent(club[3]);
infowindow.open(map, this);
});
}
}
I know I'm crappy, but someone please help me! :P
The problem is because you're setting the event listener for the marker click within a loop. So all the markers end up only getting the content for the last of your markers. Try this instead. Create a new global function:
function bindInfoWindow(marker, map, infowindow, html) {
marker.addListener('click', function() {
infowindow.setContent(html);
infowindow.open(map, this);
});
}
Then within your loop, replace this:
google.maps.event.addListener(marker, 'click', function(){
infowindow.setContent(club[3]);
infowindow.open(map, this);
});
with this:
// add an event listener for this marker
bindInfoWindow(marker, map, infowindow, club[3]);
When setting the marker object (var marker = new ...) change this line: "title: club[0]," to "title: club[i],". Yes, just change the 0 to i.
That should solve the problem.
Try this link for a tutorial on Google Maps API with examples.
http://code.google.com/apis/maps/documentation/javascript/tutorial.html
It should be very easy and helpful.

Categories

Resources