How to close an infowindow - javascript

I have already have an array of markers, I want to close an opened infowindow when I click another marker.
I know that with the v3 API, I can close a infowindow with the InfoWindow.close() method.But where to add the code?I have tried a lot but failed.
I have another question ,why need I click the link in "side_bar_div" tiwce to call the method myclick(i)?
<script type="text/javascript">
var markers=[];
var side_bar_html='<table border=0 cellpadding=0><tr>';
var tdrow = 1;
var i = 0;
function creatmarker(lat,long,map,html,index){
var mylatlng = new google.maps.LatLng(lat,long);
var marker = new google.maps.Marker({
position: mylatlng,
map: map,
zIndex: index
});
var infowindow = new google.maps.InfoWindow({
content: html
});
markers.push(marker);
side_bar_html +='<td width=330 valign=top align=left><a id="side_bar_'+i+'" href="javascript:myclick('+ (markers.length-1) +');">'+html+'</a></td>';
tdrow++;
i++;
if (tdrow > 2){side_bar_html += '</tr><tr>'; tdrow =1; }
google.maps.event.addListener(marker,'click',function(){
infowindow.open(map,marker);
});
function myclick(i){
var id="side_bar_"+i;
google.maps.event.addDomListener(document.getElementById(id), "click", function(){ google.maps.event.trigger(markers[i], "click");
});
}
function initialize(){
var myOptions = {
zoom: 11,
center: new google.maps.LatLng(-33.9, 151.2),
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("mymap"),myOptions);
var lat = "-33.890542";
var lng = "151.274856";
var html = 'Bondi Beach';
creatmarker(lat,lng,map,html,5);
var lat = "-33.923036";
var lng = "151.259052";
var html = 'Coogee Beach';
creatmarker(lat,lng,map,html,4);
var lat = "-34.028249";
var lng = "151.157507";
var html = 'Cronulla Beach';
creatmarker(lat,lng,map,html,3);
var lat = "-33.80010128657071";
var lng = "151.28747820854187";
var html = 'Manly Beach';
creatmarker(lat,lng,map,html,2);
var lat = "-33.950198";
var lng = "151.259302";
var html = 'Maroubra Beach';
creatmarker(lat,lng,map,html,1);
side_bar_html +='</tr></table>';
document.getElementById("side_bar_div").innerHTML = side_bar_html;
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>

Try the following code snippet:
var infoWindows = [];
google.maps.event.addListener(marker,'click',function(){
closeInfowindow();
var infowindow = new google.maps.InfoWindow({
content: html
});
infowindow.open(map,marker);
infoWindows[0] = infowindow;
});
function closeInfowindow(){
if(infoWindows.length > 0){
infoWindows[0].set("marker",null);
infoWindows[0].close();
infoWindows.length = 0;
}
}
Hope this helps you :-)

The correct way to do this is to store it in a local variable and then add an eventlistener like this:
function addeventlistenerinfo(marker, infowindow, i){
google.maps.event.addListener(marker, 'click', function() {
if (currentinfowindow)
currentinfowindow.close();
infowindow.open(map,marker);
currentinfowindow = infowindow;
});
markersarray[i] = marker;
}
currentinfowindow is a global variable that will only hold the open infowindow if one exists.
No need to use an array or an extra method :)

Related

Removing all showed marks Google API

I work in Laravel project and I have module for displaying and removing all stores on a Google map if I choose only 1 store.
This is a duplicate question, however, why my function is not working setting the function showallmarks as null.
Question: How to remove all the marks displayed in the google maps once a button is clicked?
I have here the codes.
Show all marks:
showallmarks();
function showallmarks() {
$.each(locations, function(index, value) {
var position = new google.maps.LatLng(value.store_lat, value.store_long);
var title = value.branch_name;
var address = value.store_address;
var contentString = "<h5>" + title + "</h5>" + address;
var infowindow = new google.maps.InfoWindow({
content: contentString
});
var marker = new google.maps.Marker({
position: position,
icon: google.maps.marker,
map: map,
zoom: 12
});
marker.addListener('click', function() {
infowindow.open(map, marker);
});
});
}
Once I click this button the showallmarks must not be shown on the Google map.
var markeronce;
$('button#addresses').click(function() {
//removing all marks
showallmarks(null);
var infowindow = new google.maps.InfoWindow({
content: "<span>Visit us on our store.</span>"
});
var address_href = $(this).val();
var commaPos = address_href.indexOf(',');
var coordinatesLat = parseFloat(address_href.substring(0, commaPos));
var coordinatesLong = parseFloat(address_href.substring(commaPos + 1, address_href.length));
var centerPoint = new google.maps.LatLng(coordinatesLat, coordinatesLong);
if (!markeronce) {
markeronce = new google.maps.Marker({
position: centerPoint,
map: map,
zoom: 8
});
} else {
markeronce.setPosition(centerPoint);
}
map.setCenter(centerPoint);
})
Add Button like
<input type="button" value="Delete" onclick="DeleteMarkers()" />
And try this function
<script type="text/javascript">
var markers = [];
function DeleteMarkers() {
//Loop through all the markers and remove
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(null);
}
markers = [];
};
</script>

google map addlistener onclick get xml data

hi I have problem with addlistener in google map
I cant get html value from xml. always return [object Element]
document.getElementById("infobox").innerHTML = html;
and infowindow.setContent(html); work perfectly
I know I do this before last 1 month ago i dont know was v3 version or this. but i do this before!
or if you know other way for getting out data please help!
from this code in addlistener
var side_bar_html = " ";
var html = " ";
var gmarkers = [];
var map = null;
/
function createMarker(latlng, name, html) {
var contentString = html;
var marker = new google.maps.Marker({
position: latlng,
map: map,
zIndex: Math.round(latlng.lat()*-100000)<<5,icon : 'mark.png'
});
google.maps.event.addListener(marker, 'click', function() {
document.getElementById("infobox").innerHTML = html;
infowindow.setContent(html);
infowindow.open(map,marker);
});
gmarkers.push(marker);
// add a line to the side_bar html
side_bar_html += '<a href="javascript:myclick(' + (gmarkers.length-1) + ')">' + name + '<\/a><br>';
}
function myclick(i) {
google.maps.event.trigger(gmarkers[i], "click");
}
function initialize() {
var myOptions = {
zoom: 11,
center: new google.maps.LatLng(38.06106741381199,46.359741),
mapTypeControl: true,
mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU},
navigationControl: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
// Read the data from example.xml
downloadUrl("example.xml", function(doc) {
var xmlDoc = xmlParse(doc);
var markers = xmlDoc.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
// obtain the attribues of each marker
var lat = parseFloat(markers[i].getAttribute("lat"));
var lng = parseFloat(markers[i].getAttribute("lng"));
var point = new google.maps.LatLng(lat,lng);
var html = markers[i].getElementsByTagName("infowindow")[0] ;
var label = markers[i].getAttribute("label");
// create the marker
var marker = createMarker(point,label,html);
}
document.getElementById("side_bar").innerHTML = side_bar_html;
// put the assembled side_bar_html contents into the side_bar div
});
}
var infowindow = new google.maps.
InfoWindow(
{
size: new google.maps.Size(150,50)
});
xml code:
<?xml version="1.0"?>
<maincontent>
<markers>
<marker lat="37.95989919257204" lng="46.38427734375" label="way 1">
<infowindow>station 1</infowindow>
</marker>
</markers>
</maincontent>
I found what is problem just change tag to attribute!
var html = markers[i].getAttribute("html");
But I dont know why!

google maps infowindow positioning with polylines

I have a map with multiple polylines which I am looking to display infowindow for each line. I have the infowindow working but it is not positioning to the event click as it should be. Instead, each window displays in the same place. Can't seem to track down the root of the issue.
<script type="text/javascript">
var contentString = "";
var infowindow = new google.maps.InfoWindow({
content: contentString,
});
function initialize() {
var myLatlng = new google.maps.LatLng(30.695895, -97.354080);
var mapOptions = {
zoom: 5,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.TERRAIN,
};
var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
downloadUrl("data.xml", function(data) {
var xml = xmlParse(data);
var polylines = xml.documentElement.getElementsByTagName("polyline");
var polylineData = new Array();
for (var i = 0; i < polylines.length; i++) {
polylineData[i] = {id:polylines[i].getAttribute("id"),
name:polylines[i].getAttribute("name"),
olat:polylines[i].getAttribute("olat"),
olng:polylines[i].getAttribute("olng"),
dlat:polylines[i].getAttribute("dlat"),
dlng:polylines[i].getAttribute("dlng")}
}
for (var j = 0; j < polylineData.length; j++) {
var path = [
new google.maps.LatLng(parseFloat(polylineData[j].olat), parseFloat(polylineData[j].olng)),
new google.maps.LatLng(parseFloat(polylineData[j].dlat), parseFloat(polylineData[j].dlng))
];
var polyline = new google.maps.Polyline({
path: path,
strokeWeight: 2
});
google.maps.event.addListener(polyline, 'click', (function(event,index){
return function(){
infowindow.content = '<div class="infobox" style="width:280px;"><span class="name">' + polylineData[index].name + '</span></div>';
var point = event.latLng;
infowindow.setPosition(point);
infowindow.open(map);
};
})(event,j));
polyline.setMap(map);
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
XML data looks like this:
<polylines>
<polyline id="176" name="Line Name" olat="53.545204" olng="-113.369492" dlat="53.545204" dlng="-113.369492"/>
</polylines>
I have read some similar posts but none of the answers have worked in this case thus far. Thanks!
event must be the argument passed to the returned function:
google.maps.event.addListener(polyline, 'click', (function(index){
//_________________________________________________________^:the index of the item
return function(event){
//________________^:the event
infowindow.content = '<div class="infobox" style="width:280px;"><span class="name">' + polylineData[index].name + '</span></div>';
var point = event.latLng;
infowindow.setPosition(point);
infowindow.open(map);
};
})(j));

Google map clickable infowindows from markers

I have this script for links from google map markers:
<script type="text/javascript">
var locations = [['Test 1','55','13','url1'],['Test 2','45','17','url2']];
function initialize()
{
var myOptions = {
center: new google.maps.LatLng(50,15),
zoom: 3,
mapTypeId: google.maps.MapTypeId.SATELLITE};
var map = new google.maps.Map(document.getElementById("map"),myOptions);
setMarkers(map,locations)
}
function setMarkers(map,locations)
{
var marker, i
for(i = 0; i < locations.length; i++)
{
var arr = i
var name = locations[i][0]
var lat = locations[i][1]
var long = locations[i][2]
var adress = locations[i][3]
latlngset = new google.maps.LatLng(lat, long);
var marker = new google.maps.Marker({
map: map,
title: name,
url: adress,
position: latlngset
});
google.maps.event.addListener(marker, 'click', function() {window.location.href = this.url;});
}
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
...and, I need generate infowindows from markers instead of links, do you have any simple idea?
Google map clickable infowindows from markers

Every infowindow is displaying the same data maps api v3

I am really stuck on something. Every map marker's infowindow is displaying the same info. It seems to be the content at the end of an array that i use to store content nodes every time. I am pretty sure it is because the infowindow is not being attached to the proper marker
var markers = [];
var contentArray = [];
var titleArray = [];
var latlngArray = [];
var map;
//var infowindow;
var concert;
function defaultMap()
{
//Latitude: 38
//Longitude: -97
//window.alert("inside function");
var mapOptions = {
center:new google.maps.LatLng(38,-97),
zoom:4,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map"),
mapOptions);
// window.alert("addMarkers the size of contentArray is: "+contentArray.length);
//window.alert("addMarkers the size of the titleArray is: "+titleArray.length);
// window.alert("addMarkers the size of the latLongArray is: "+latlngArray.length);
//for(var i =0;i<2;i++)
//{
// if(i == 0)
// {
// marker = new google.maps.Marker({
// position: new google.maps.LatLng(37.8172784,-96.8909115),
// map:map
// });
// markers.push(marker);
// }
// else
// {
// marker = new google.maps.Marker({
// position: new google.maps.LatLng(37.8172973,-96.8766355),
// map:map
// });
// markers.push(marker);
// }
// //markers[0] = new google.maps.LatLng(37.8172784,-96.8909115);
// //markers[1] = new google.maps.LatLng(37.8172973,-96.8766355);
//
//}
//addMarkers();
}
//function
//
//{
//infowindow = new google.maps.InfoWindow({
//content:list
//});
//google.maps.event.addListener(marker,'click',function(){
// infowindow.open(map,marker);
//});
function addMarkers()
{
//console.dir(contentArray[contentArray.length-1]);
for(var i = 0;i <10;i++)
{
if(i == 0)
{
//window.alert("i = "+i);
console.log(latlngArray[i]);
var marker = new google.maps.Marker({
position:latlngArray[i],
animation:google.maps.Animation.DROP,
icon:'./images/club.png',
title:titleArray[i],
map:map
});
//marker.setMap(map);
var infowindow = new google.maps.InfoWindow({
});
google.maps.event.addListener(marker,'click',function()
{
//console.log(infowindow.getContent());
infowindow.setContent(contentArray[i]);
infowindow.open(map,this);
});
markers.push(marker);
}
else
{
console.log(latlngArray[i]);
var marker = new google.maps.Marker({
position:latlngArray[i],
animation:google.maps.Animation.DROP,
icon:'./images/restaurant.png',
title:titleArray[i],
map:map
});
var infowindow = new google.maps.InfoWindow({});
//console.log(infowindow.getContent());
google.maps.event.addListener(marker,'click',function()
{
infowindow.setContent(contentArray[i]);
console.log(infowindow.getContent());
infowindow.open(map,this);
});
markers.push(marker);
}
//console.log(i);
//console.log(contentArray[i]);
}
}
The problem is that when the loop ends, i is 10.
Every infowindow displays:
infowindow.setContent(contentArray[i]);
There are two ways to solve the problem:
function closure. Use a createMarker function to associate the infowindow content with the marker. Explained in Mike Williams' v2 tutorial, one of his examples using function closure, translated to v3.
marker member variable containing the content, access it in the click listener by referencing "this". The answer to this similar question may help with this. Here is an example of using a member variable of the marker
This Code is also for all those who want to put multiple Markers on Map retrieved from DB
i am going to paste a Code of live project means working. you can get some help from this.
function latLongCallback(latitutde,longitutde){
var latlng = new google.maps.LatLng(latitutde, longitutde);
var options = {zoom: 4, center: latlng, mapTypeId: google.maps.MapTypeId.ROADMAP};
var map = new google.maps.Map(document.getElementById('map'), options);
$.ajax({type: "GET",
dataType: 'json',
url: 'https://www.xyz.com/yourrfolder/markers.php',
success: function(response){
var total=response.length;
var data_array,name,type,address,lat,lon,arrival,departure,notes;
var infowindow = new google.maps.InfoWindow();
for(var i=0; i < total; i++){
data_array=response[i];
name=data_array['name'];
id = data_array['id'];
address=data_array['address'];
arrival=data_array['arrival'];
departure=data_array['departure'];
notes=data_array['notes'];
lat=data_array['lat'];
lon=data_array['lon'];
icon=data_array['icon'];
sc_id=data_array['sc_id'];
var propPos = new google.maps.LatLng(lat,lon);
propMarker = new google.maps.Marker({
position: propPos,
map: map,
icon: icon,
zIndex: 3
});
var contentString = "<div style='font-size:9px;overflow:hidden'>"+name+"<br/><label class='label'>Location :</label> "+address+"<br/><label class='label'>Arrival :</label> "+arrival+"<br/><label class='label'>Departure :</label> "+departure+"<br/><label class='label'>Notes :</label> "+notes + "</div><div style='font-size:9px;overflow:hidden'><a href='#2' onclick="+xx+" class='popup-txt' style='font-size:11px; margin-top:3px;'>Message him</a><a href='#1' onclick="+invite+" class='popup-txt' style='font-size:11px; margin-top:3px; float:right;'>Invite Friend</a></div>";
function bindInfoWindow(marker, map, infowindow, html) {
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(html);
infowindow.open(map, marker);
});
bindInfoWindow(propMarker, map, infowindow, contentString);
}
}
});
return;
}
and here is the marker.php mentioned in above js
<?php
$data=array();
$retrive_marker_query = "your query";
$result = db_execute($retrive_marker_query);
$cnt=0;
while ($row = mysql_fetch_assoc($result)){
$name = $row['name'];
$id = $row['fb_id'];
$sc_id = $row['id'];
$address = $row['location'];
$lat = $row['lat'];
$lon = $row['lon'];
$data[$cnt]['name'] = $name;
$data[$cnt]['id'] = $id;
$data[$cnt]['sc_id'] = $sc_id;
$data[$cnt]['address'] = $address;
$data[$cnt]['lat'] = $lat;
$data[$cnt]['lon'] = $lon;
$cnt++;
}
$data=json_encode($data);
echo($data);
<?

Categories

Resources