Detecting Google map being closed and Google map infowindow being closed - javascript

I am trying to create a map dialog which allows the user to select his or her desired location.
I have a working example located at http://jsfiddle.net/HCUPa/1/, and the source code is below.
When the infowindow is closed (by clicking the X on the infowindow), how do I remove the associated marker? Do I then need to remove the infowindows name from the array, and if so, how?
Also, when the map (or dialog and then the map) is closed, how do I detect it being closed, and should I be cleaning up any resources, and if so what and how?
I attempted to use addListeners for both as shown in my example, but it isn't working.
Lastly, not really my formal question, but I would appreciate any advise whether I am generally doing this correct. This was my first attempt of the Google map api, and I am still a JavaScript novice, and would appreciate any suggestions, criticize, etc.
Thank you
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<style type="text/css">
#googleMap { height: 100%;width: 100%;}
div.modify-title-bar div.ui-dialog-titlebar {border:0;background-image:none;background-color:transparent;padding:0;margin:0;}
#dialog-map,div.modify-title-bar {padding:0;margin:0;}
</style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<link type="text/css" href="http://code.jquery.com/ui/1.9.0/themes/base/jquery-ui.css" rel="stylesheet" />
<script src="http://code.jquery.com/ui/1.9.0/jquery-ui.js"></script>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDY0kkJiTPVd2U7aTOAwhc9ySH6oHxOIYM&sensor=false"></script>
<script type="text/javascript">
function createMap(geocoder,myCenter,address) {
var map = new google.maps.Map(document.getElementById("googleMap"),{center:myCenter,zoom:5,mapTypeId:google.maps.MapTypeId.ROADMAP});
var marker = new google.maps.Marker({position: myCenter,map: map,});
var infowindow = new google.maps.InfoWindow({content: '<span>'+address+'</span><br><button class="accept">Select Address</button>'});
infowindow.open(map,marker);
google.maps.event.addListener(map, 'close', function(event) {
//How do I detect map closing, what and how should I clean up? Maybe move to dialog close?
alert('close map');
delete geocoder,myCenter,address,map,marker,infowindow;
});
google.maps.event.addListener(map, 'click', function(event) {
marker.setMap(null);
marker = new google.maps.Marker({
position: event.latLng,
map: map,
});
geocoder.geocode({location: event.latLng}, function(GeocoderResult, GeocoderStatus) {
infowindow.close();
infowindow = new google.maps.InfoWindow({content: '<span>'+GeocoderResult[0].formatted_address+'</span><br><button class="accept">Select Address</button>'});
infowindow.open(map,marker);
});
google.maps.event.addListener(infowindow,'closeclick',function(){
//How do I detect if infowindow is closed? Do I then need to remove the infowindows name from the array, and if so, how?
alert('Remove marker');
marker.setMap(null);
});
});
}
$(function(){
$("#googleMap").on("click", "button.accept", function(){
$('#address').val($(this).parent().children('span').eq(0).text());
$("#dialog-map").dialog('close');
});
$("#findIt").click(function(){$("#dialog-map").dialog("open");return false;});
$("#dialog-map").dialog({
autoOpen : false,
resizable : false,
height : 500,
width : 800,
modal : true,
dialogClass : 'modify-title-bar',
open : function() {
var address=$.trim($('#address').val()),
geocoder=new google.maps.Geocoder,
LatLng,
//Default LatLng
Ya=47.6204901, Za=-122.34964839999998,
//Give default address to limit geocoder calls
default_address='400 Broad Street, Seattle, WA 98109, USA';
if(address) {
geocoder.geocode({address: address}, function(GeocoderResult, GeocoderStatus) {
if (GeocoderStatus=='OK') {
LatLng=GeocoderResult[0].geometry.location;
}
else {
LatLng=new google.maps.LatLng(Ya,Za);
adderss=default_address;
}
createMap(geocoder,LatLng,address);
});
}
else {
LatLng=new google.maps.LatLng(Ya,Za);
createMap(geocoder,LatLng,default_address);
}
}
});
});
</script>
</head>
<body>
<button id="findIt">Find it on a map</button>
<input id="address" type="text" value="1600 Pennsylvania Avenue Northwest Washington, DC">
<div id="dialog-map" title="Select a location">
<div id="googleMap"></div>
</div>
</body>
</html>

Create a new function that listens for the infowindow close event
function infowindowClose(infowindow, marker) {
google.maps.event.addListenerOnce(infowindow, 'closeclick', function() {
marker.setMap(null);
});
}
Call that everytime you create a new infowindow.
Working Demo
You are doing well for your first time using the API. If you want more than one marker and infobox then you will need to make a few changes, otherwise it's fine.

Related

How to add a click event handler to a google maps api marker object using jQuery?

My HTML is :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="style.css">
<title>MapTest</title>
</head>
<body>
<div id="mapContainer"></div>
<script type="text/javascript" src="scripts/jquery-3.1.0.min.js"></script>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=AIzaSyB1KzIyYJuVoPB84Rum7kH5uUETV-WIgSA"></script>
<script type="text/javascript" src="scripts/maps.js"></script>
</body>
</html>
My CSS is:
#mapContainer {
width : 500px;
height: 500px;
}
My jQuery is:
$(document).ready(function() {
var lat = 22.688138;
var lng = 88.343926;
function initMap()
{
var latlng = new google.maps.LatLng(lat, lng);
var mapOpts = {
center : latlng,
zoom : 20,
mapTypeId : google.maps.MapTypeId.HYBRID
};
var map = new google.maps.Map(document.getElementById("mapContainer"),mapOpts);
var marker = new google.maps.Marker({
position : latlng,
map : map,
title : "Somu's House, Bitches!"
});
var infoWindow = new google.maps.InfoWindow({
content : "Somu's House, Bitches!"
});
$(marker).click(function() {
infoWindow.open(map, marker);
});
}
initMap();
});
The point of interest is the following lines
$(marker).click(function() {
infoWindow.open(map, marker);
});
The above code doesn't work (despite not generating any errors or warnings). However, according to the JavaScript API's sample code, the correct JS code is:
marker.addListener('click', function() {
infoWindow.open(map, marker);
});
Why does the original code not work? How do I convert the above code to jQuery? What is the correct way of achieving the same in jQuery?
marker is a google.maps.Marker instance. It's not a DOM element. So $(marker).click() doesn't work as you expect. (You are not clicking the "marker object")
Using marker's addListener method is the correct way to achieve it.

Google maps infowindow display kml object name and link

I have some working code to display a KML layer on Google maps. When you click on the various parts of the layer their respective name pops up in an info window.
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0; padding: 0 }
#map-canvas { height: 100% }
</style>
<script type="text/javascript"
// Load Google Maps API
src="https://maps.googleapis.com/maps/api/js?key=XXXXXXXXXXX&sensor=false">
</script>
<script type="text/javascript">
function initialize() {
var myLatlng = new google.maps.LatLng(51.875696, -0.624207);
var mapOptions = {
zoom: 6,
center: myLatlng
};
var map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
var kmlLayer = new google.maps.KmlLayer({
url: 'http://XXXXXXX.org/gliding/grid3.kml',
suppressInfoWindows: false,
map: map
});
google.maps.event.addListener(kmlLayer, 'click', function(kmlEvent) {
var text = kmlEvent.featureData.name;
showInContentWindow(text);
});
function showInContentWindow(text) {
var sidediv = document.getElementById('content-window');
}
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas" style="width:100%; height:100%; float:left"></div>
</body>
</html>
I would like the info window to also contain a link to a page with the same name as object clicked on. For example if the user clicks on a shape in the KML layer called Tom the info window says Tom Click Here. If the user clicks the link they are taken to www.XYZ.com/Tom.
I'm sure this is quite simple, but I'm new to javascript and can't get it to work.
This is more a hack than a solution (which means google could change a property name and this would stop working.
However, here you go
google.maps.event.addListener(kmlLayer, 'click', function(kmlEvent) {
var text = kmlEvent.featureData.name;
kmlEvent.featureData.infoWindowHtml += 'Click Here';
showInContentWindow(text);
});

Markers not showing until map moved slightly or clicked

my (cut down) code is as below. My markers are not showing up until I either click or move the map slightly... is there any way of getting around this so they show up instantly?
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>TSF - Labour Plan </title>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"> </script>
<script type="text/javascript">
function initialize() {
var centerlatlng = new google.maps.LatLng(53.644638, -2.526855);
var myOptions = {
zoom: 6,
center: centerlatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var latlng = new google.maps.LatLng(51.752927, -0.470095);
var img = "https://dl.dropboxusercontent.com/u/55888592/tsf-logo.gif";
var info = "<img style = 'float: left' src='http://www.tsf.uk.com/wp-content/themes/default/images/tsf-logo.gif'><div style = 'float: right; width: 200px'><p><b>Job Number:</b> </p><p><b>Client:</b> ASDA</p><p><b>Location:</b> HEMEL HEMPSTEAD</p><p><b>Postcode:</b> HP2 4AA</p><p><b>Start Time:</b> 22:0</p><p><b>No of Men:</b> 10.0</p><p><b>Allocated Labour:</b> AB: 5.0, WK: 5.0, : , : , : , : </p><p><b>Job Information: </b>PICK UP TOOLS</div>";
var infowindow = new google.maps.InfoWindow({
});
var marker = new google.maps.Marker({
icon: img,
position: latlng,
map: map,
content: info
});
marker.setMap(map);
google.maps.event.addListener(marker, "click", function(content) {
infowindow.setContent(this.content);
infowindow.open(map,this);
});
}
google.maps.event.addDomListener(window, "load", initialize);
</script>
</head>
<body style="margin:0px; padding:0px;" onload="initialize()">
<div id="map_canvas" style="width: 100%; height: 100%;"></div>
</body>
</html>
It seems that the problem is still exists in google chrome in most recent version on google map api and marker cluster js.
So I'll post the code which helped in this issue for me.
google.maps.event.addListener(map, 'zoom_changed', function() {
setTimeout(function() {
var cnt = map.getCenter();
cnt.e+=0.000001;
map.panTo(cnt);
cnt.e-=0.000001;
map.panTo(cnt);
},400);
});
feel free to play with value of interval of 400 (in my case less than 400 woudn't fix problem, but higher value - higher lag time)
P.S.
make sure you have defined map variable:
map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
I was struggling with the EXACTLY same problem and was so glad to hear other guys have the same problem. I experienced the problem with GMaps V3 in Safari and Firefox as well. I tried your solution and it works for me as well but I used the idle event instead the timeout:
google.maps.event.addListener(map, 'idle', function(event) {
var cnt = map.getCenter();
cnt.e+=0.000001;
map.panTo(cnt);
cnt.e-=0.000001;
map.panTo(cnt);
});
Just add it on initializing Google Maps. There might come up another issue working with infowindows and circles bound to markers. In my case I can set the radius of the circle in the infobox. Jumping out of the input field (with or without changing the radius value) makes red-like markers blue. If you then zoom in/out the original color reappears. To solve this problem you have to change the zoom level quickly (in radius_changed event):
map.setZoom(map.getZoom()-1);
map.setZoom(map.getZoom()+1);
I've resolved this calling repaint on markerclusterer variable twice:
mc.repaint();
map.fitBounds(bounds); // for centering within the marker bounds
mc.repaint(); // repaint for getting it fixed
Hope this helps to anyone still facing the issue.
As per Geocodezips comment, this seems to be a local issue.

Embedding a Google map

I have embedded a Google Map in my website. I want to change its location according to user input. How can I do this?
I tried to copy the link of the location and assign it to the iframe src:
$("iframe").attr("src", "https://maps.google.co.in/maps?q=USA&hl=en&ll=37.09024,-95.712891&spn=131.016476,346.289063&sll=23.259933,77.412615&sspn=0.178842,0.338173&oq=usa&doflg=ptm&hnear=United+States&t=m&z=2");
but the iframe is not loading the map.
Try to use the GoogleMaps JavaScript API. The offer way more control (geocode, searching, custom marker, etc...) over the map then just embedding a iframe.
Take a look at this :)
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<link href="http://code.google.com/apis/maps/documentation/javascript/examples/default.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
// Initiate map
function initialize(data) {
// Make position for center map
var myLatLng = new google.maps.LatLng(data.lng, data.lat);
// Map options
var myOptions = {
zoom: 10,
center: myLatLng,
mapTypeId: google.maps.MapTypeId.HYBRID
};
// Initiate map
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
// Info window element
infowindow = new google.maps.InfoWindow();
// Set pin
setPin(data);
}
// Show position
function setPin(data) {
var pinLatLng = new google.maps.LatLng(data.lng, data.lat);
var pinMarker = new google.maps.Marker({
position: pinLatLng,
map: map,
data: data
});
// Listen for click event
google.maps.event.addListener(pinMarker, 'click', function() {
map.setCenter(new google.maps.LatLng(pinMarker.position.lat(), pinMarker.position.lng()));
map.setZoom(18);
onItemClick(event, pinMarker);
});
}
// Info window trigger function
function onItemClick(event, pin) {
// Create content
var contentString = pin.data.text + "<br /><br /><hr />Coordinate: " + pin.data.lng +"," + pin.data.lat;
// Replace our Info Window's content and position
infowindow.setContent(contentString);
infowindow.setPosition(pin.position);
infowindow.open(map)
}
</script>
</head>
<body onload="initialize({lat:-3.19332,lng:55.952366,text:'<h2>Edinburgh</h2><i>Nice city!</i>'})">
<div id="map_canvas">
</div>
</body>
</html>

Javascript google maps

I have multiple locations of my company's regional offices and have to show each location whenever user clicks at a locations like:
location1
location2
location3
When user clicks at location 1 it will show location 1 on the map. I also have those locations in my maps. I have never worked with Google maps before, so I just need some idea to get started.
When your user clicks a link, run a piece a javascript that calls setCenter(latlng:LatLng) on the map to center the map to a certain location.
If you really don't know where to begin, then start by reading the Google Maps API documentation. It's easy to read, and it contains lots of working examples.
You can do something like this: (I'm sure it could be optimized with a for loop, its early/late right now.
<html>
<head>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
function initialize() { //Initalize JS after onload
var map = new google.maps.Map(document.getElementById('map_canvas'), {
mapTypeId: google.maps.MapTypeId.ROADMAP,
});
var randomPoint1 = new google.maps.LatLng(44.6479, -63.5744); //First Location
var marker1 = new google.maps.Marker({ //Set up marker
position: randomPoint1,
map: map
});
google.maps.event.addDomListener(document.getElementById('locationid1'), 'click', //Set up DOM listener 1
function(){
map.setZoom(13);
map.setCenter(marker1.getPosition());
});
var randomPoint2 = new google.maps.LatLng(45.5081, -73.5550); //Second Location
var marker2 = new google.maps.Marker({
position: randomPoint2,
map: map
});
google.maps.event.addDomListener(document.getElementById('locationid2'), 'click',//Set up DOM listener 2
function(){
map.setZoom(13);
map.setCenter(marker2.getPosition());
});
var randomPoint3 = new google.maps.LatLng(43.6481, -79.4042); //Third Location
var marker3 = new google.maps.Marker({
position: randomPoint3,
map: map
});
google.maps.event.addDomListener(document.getElementById('locationid3'), 'click', //Set up DOM listener 3
function(){
map.setZoom(13);
map.setCenter(marker3.getPosition());
});
map.setCenter(marker2.getPosition());
map.setZoom(5);
}
</script>
</head>
<body onload="initialize()"> <!--Initalize JS after onload--->
Halifax
Montreal
Toronto
<div id="map_canvas" style="height:100%; width:100%"></div>
</body>
</html>
And after I write this I realize the post was from last August. Oh well, may help someone at some point.

Categories

Resources