Search box on Google Maps API - google-maps

I am trying to put a search box onto my map, but it keeps failing. I have tried to use sample code from a few sites (here: How to add Google Maps Autocomplete search box?; here: How to integrate SearchBox in Google Maps JavaScript API v3?; here: https://developers.google.com/maps/documentation/javascript/examples/places-searchbox; and a tutorial from here: https://www.youtube.com/watch?v=lSdM3yZkj1w). But I can't seem to make it work, and now my map won't even display.
To explain fully, I am trying to make a map that displays a kml (which can be toggled), a marker that can be dragged by the user (which displays co-ordinates where ever the marker is), and a search box to search for an address or co-ordinates (...this is still eluding me).
In the end, I am hoping to move the search box and the kml toggle onto the map, rather than outside.
I'm very new to this, so I apologise in advance for my lack of experience. Any help would be greatly appreciated!
Non-working code below:
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3.exp&libraries=places"></script>
<script type="text/javascript">
var map = null;
var geocoder = new google.maps.Geocoder();
var layers=[];
layers[0] = new google.maps.KmlLayer("https://dl.dropboxusercontent.com/u/29079095/Limpopo_Hunting_Zones/Zones_2015.kml",
{preserveViewport: true});
function toggleLayers(i)
{
if(layers[i].getMap()==null){
layers[i].setMap(map);
}
else {
layers[i].setMap(null);
}
}
function geocodePosition(pos) {
geocoder.geocode({
latLng: pos
}, function(responses) {
if (responses && responses.length > 0) {
updateMarkerAddress(responses[0].formatted_address);
} else {
updateMarkerAddress('Cannot determine address at this location.');
}
});
}
function updateMarkerStatus(str) {
document.getElementById('markerStatus').innerHTML = str;
}
function updateMarkerPosition(latLng) {
document.getElementById('info').innerHTML = [
latLng.lat(),
latLng.lng()
].join(', ');
}
function updateMarkerAddress(str) {
document.getElementById('address').innerHTML = str;
}
function initialize() {
var latLng = new google.maps.LatLng(-23.742023, 29.462218);
var markerPosition = new google.maps.LatLng(-23.460136, 31.3189074);
map = new google.maps.Map(document.getElementById('mapCanvas'), {
zoom: 7,
center: latLng,
mapTypeId: google.maps.MapTypeId.TERRAIN
});
var marker = new google.maps.Marker({
position: markerPosition,
title: 'Point A',
map: map,
draggable: true
});
// Update current position info.
updateMarkerPosition(latLng);
geocodePosition(latLng);
// Add dragging event listeners.
google.maps.event.addListener(marker, 'dragstart', function() {
updateMarkerAddress('DRAGGING...');
});
google.maps.event.addListener(marker, 'drag', function() {
updateMarkerStatus('DRAGGING...');
updateMarkerPosition(marker.getPosition());
});
google.maps.event.addListener(marker, 'dragend', function() {
updateMarkerStatus('DRAG & DROP THE MARKER ONTO YOUR DESIRED PROPERTY');
geocodePosition(marker.getPosition());
});
}
var defaultBounds = new google.maps.LatLngBounds(
new google.maps.LatLng(-25.43029134371126, 25.979551931249944),
new google.maps.LatLng(-21.919517708560267, 32.164854665624944));
var options = {
bounds: defaultBounds
};
var input = document.getElementById('pac-input');
map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
var searchBox = new google.maps.places.SearchBox(input, options);
google.maps.event.addListener(searchBox, 'places_changed', function() {
var places = searchBox.getPlaces();
if (places.length == 0) {
return;
}
for (var i = 0, marker; marker = markers[i]; i++) {
marker.setMap(null);
}
markers = [];
var bounds = new google.maps.LatLngBounds();
for (var i = 0, place; place = places[i]; i++) {
var image = {
url: place.icon,
size: new google.maps.Size(71, 71),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(17, 34),
scaledSize: new google.maps.Size(25, 25)
};
var marker = new google.maps.Marker({
map: map,
icon: image,
title: place.name,
position: place.geometry.location
});
markers.push(marker);
bounds.extend(place.geometry.location);
}
map.fitBounds(bounds);
});
google.maps.event.addListener(map, 'bounds_changed', function() {
var bounds = map.getBounds();
searchBox.setBounds(bounds);
});
}
// Onload handler to fire off the app.
google.maps.event.addDomListener(window, 'load', initialize);
</script>
<style>
#mapCanvas {
width: 1000px;
height: 500px;
float: top;
}
#infoPanel {
float: top;
margin-left: 10px;
}
#infoPanel div {
margin-bottom: 5px;
}
</style>
</head>
<body>
<input id="pac-input" class="controls" type="text" placeholder="SEARCH">
<div id="map-canvas"></div>
CLICK TO DISPLAY ZONES <input type="checkbox" id="CLICK TO HUNTING ZONES" onclick="toggleLayers(0);"/>
<div id="mapCanvas"></div>
<div id="infoPanel">
<div id="address"></div>
<b>MARKER STATUS:</b>
<div id="markerStatus"><i>DRAG & DROP THE MARKER ONTO YOUR DESIRED PROPERTY.</i>
</div>
<b>GPS CO-ORDINATES:</b>
<div id="info"></div>

Related

Google Map add marker from two text boxes values (lat & lng)

I have an app where the user clicks on the map to create a marker and store it in the database.
This code under my question works fine, but now I would like to add a function to display a marker from lat and lng values ​​contained in two text boxes (camera_lat and camera_long) imported from the database.
Does anyone know how to do that ?
let map;
var marker;
function initmap() {
var latlng = new google.maps.LatLng(43.920340, 7.1325917);
var myOptions = {
zoom: 9,
center: latlng,
gestureHandling: 'greedy'
};
map = new google.maps.Map(document.getElementById("div_map"), myOptions);
google.maps.event.addListener(map, "click", function(event) {
// get lat/lon of click
clickLat = event.latLng.lat();
clickLon = event.latLng.lng();
// show in input box
document.getElementById("camera_lat").value = clickLat.toFixed(5);
document.getElementById("camera_long").value = clickLon.toFixed(5);
// if marker exist remove it show only one marker
if(marker != null){
marker.setMap(null);
}
marker = new google.maps.Marker({
position: new google.maps.LatLng(clickLat,clickLon),
map: map
});
});
}
google.maps.event.addDomListener(window, 'load', initmap);
Take the values from the input fields, use them to make a google.maps.LatLng object, use that to position the marker.
make a function to add the marker:
function addMarker(latLng, map) {
// if marker exist remove it show only one marker
if (marker != null) {
marker.setMap(null);
}
marker = new google.maps.Marker({
position: latLng,
map: map
});
}
if you want to add the marker on page load (and have data in the input fields at that time, call the function after instantiating the map:
var lat = document.getElementById("camera_lat").value;
var lng = document.getElementById("camera_long").value;
addMarker(new google.maps.LatLng(lat, lng), map);
then use that in the existing code and in a click listener function on a button to add the marker:
google.maps.event.addDomListener(document.getElementById('btn'), 'click', function() {
var lat = document.getElementById("camera_lat").value;
var lng = document.getElementById("camera_long").value;
addMarker(new google.maps.LatLng(lat, lng), map);
});
proof of concept fiddle
code snippet:
let map;
var marker;
function initmap() {
var latlng = new google.maps.LatLng(43.920340, 7.1325917);
var myOptions = {
zoom: 9,
center: latlng,
gestureHandling: 'greedy'
};
map = new google.maps.Map(document.getElementById("div_map"), myOptions);
var lat = document.getElementById("camera_lat").value;
var lng = document.getElementById("camera_long").value;
addMarker(new google.maps.LatLng(lat, lng), map);
google.maps.event.addListener(map, "click", function(event) {
// get lat/lon of click
clickLat = event.latLng.lat();
clickLon = event.latLng.lng();
// show in input box
document.getElementById("camera_lat").value = clickLat.toFixed(5);
document.getElementById("camera_long").value = clickLon.toFixed(5);
addMarker(event.latLng, map);
});
google.maps.event.addDomListener(document.getElementById('btn'), 'click', function() {
var lat = document.getElementById("camera_lat").value;
var lng = document.getElementById("camera_long").value;
addMarker(new google.maps.LatLng(lat, lng), map);
});
}
function addMarker(latLng, map) {
// if marker exist remove it show only one marker
if (marker != null) {
marker.setMap(null);
}
marker = new google.maps.Marker({
position: latLng,
map: map
});
}
google.maps.event.addDomListener(window, 'load', initmap);
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#div_map {
height: 90%;
}
/* Optional: Makes the sample page fill the window. */
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
<!DOCTYPE html>
<html>
<head>
<title>Simple Map</title>
<script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
<!-- jsFiddle will insert css and js -->
</head>
<body>
<input id="camera_lat" value="43.661" />
<input id="camera_long" value="6.90188" />
<input id="btn" value="add marker" type="button" />
<div id="div_map"></div>
<!-- Async script executes immediately and must be after any DOM elements used in callback. -->
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
</body>
</html>

how to calculate the number of marker inside manually drawn polygon on google map

I have a map where there can be n number of marker plotted on the google map, when the user draw the polygon on the map I need to know the makers plotted inside the polygon.
I tried to draw the polygon on the map which is as shown below
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js"> </script>
<style>
html,body{height:100%;margin:0}
#map_canvas{height:90%;}
</style>
<script>
function initialize() {
var myLatLng = {lat: 52.5498783, lng: 13.425209099999961};
var mapOptions = {
zoom: 14,
center: new google.maps.LatLng(52.5498783, 13.425209099999961),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
title: 'Hello World!'
});
google.maps.event.addDomListener(map.getDiv(),'mousedown',function(e){
//do it with the right mouse-button only
if(e.button!=2)return;
//the polygon
poly=new google.maps.Polyline({map:map,clickable:false});
//move-listener
var move=google.maps.event.addListener(map,'mousemove',function(e){
poly.getPath().push(e.latLng);
});
//mouseup-listener
google.maps.event.addListenerOnce(map,'mouseup',function(e){
google.maps.event.removeListener(move);
var path=poly.getPath();
poly.setMap(null);
poly=new google.maps.Polygon({map:map,path:path});
});
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
Use the right mouse-button to draw an overlay<br/>
<div id="map_canvas"></div>
</body>
</html>
use right mouse button to draw
for now I have only one marker, how to find the number of markers inside the polygon and their latitude and longitude the polygons can be of any shape on the map.
You could utilize containsLocation() function to determine whether marker is located inside a polygon or not.
This example draws a green polygon when the marker falls outside of the specified polygon, and a red polygon when the marker falls inside the polygon.
function initialize() {
var myLatLng = { lat: 52.5498783, lng: 13.425209099999961 };
var mapOptions = {
zoom: 14,
center: new google.maps.LatLng(52.5498783, 13.425209099999961),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
title: 'Hello World!'
});
google.maps.event.addDomListener(map.getDiv(), 'mousedown', function (e) {
//do it with the right mouse-button only
if (e.button != 2) return;
//the polygon
var poly = new google.maps.Polyline({ map: map, clickable: false });
//move-listener
var move = google.maps.event.addListener(map, 'mousemove', function (e) {
poly.getPath().push(e.latLng);
});
//mouseup-listener
google.maps.event.addListenerOnce(map, 'mouseup', function (e) {
google.maps.event.removeListener(move);
var path = poly.getPath();
poly.setMap(null);
poly = new google.maps.Polygon({ map: map, path: path });
var resultColor = google.maps.geometry.poly.containsLocation(marker.getPosition(), poly) ? 'green' : 'red';
poly.setOptions({ fillColor: resultColor, strokeOpacity: 0.5 });
});
});
}
google.maps.event.addDomListener(window, 'load', initialize);
html, body {
height: 100%;
margin: 0;
}
#map_canvas {
height: 90%;
}
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?&libraries=geometry"> </script>
Use the right mouse-button to draw an overlay<br />
<div id="map_canvas"></div>
To get the number of markers inside the polygon, one option is to keep references to them in array, then iterate through that array checking to see if the marker is in the polygon or not. To determine if a marker is inside the polygon, the geometry library poly namespace method containsLocation can be used:
var markerCnt = 0;
for (var i = 0; i < markers.length; i++) {
if (google.maps.geometry.poly.containsLocation(markers[i].getPosition(), poly)) {
markerCnt++;
}
}
document.getElementById('numberMarkers').innerHTML += "There are " + markerCnt + " markers in the polygon<br>";
proof of concept fiddle
code snippet:
var markers = [];
function initialize() {
var myLatLng = {
lat: 52.5498783,
lng: 13.425209099999961
};
var mapOptions = {
zoom: 5,
center: new google.maps.LatLng(52.5498783, 13.425209099999961),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
title: 'Hello World!'
});
markers.push(marker);
google.maps.event.addListener(map, 'bounds_changed', makeRandomMarkers);
var poly;
google.maps.event.addDomListener(map.getDiv(), 'mousedown', function(e) {
//do it with the right mouse-button only
if (e.button != 2) return;
//the polygon
if (poly && poly.setMap) {
poly.setMap(null);
}
poly = new google.maps.Polyline({
map: map,
clickable: false
});
//move-listener
var move = google.maps.event.addListener(map, 'mousemove', function(e) {
poly.getPath().push(e.latLng);
});
//mouseup-listener
google.maps.event.addListenerOnce(map, 'mouseup', function(e) {
google.maps.event.removeListener(move);
var path = poly.getPath();
poly.setMap(null);
poly = new google.maps.Polygon({
map: map,
path: path
});
var markerCnt = 0;
for (var i = 0; i < markers.length; i++) {
if (google.maps.geometry.poly.containsLocation(markers[i].getPosition(), poly)) {
markerCnt++;
}
}
document.getElementById('numberMarkers').innerHTML = "There are " + markerCnt + " markers in the polygon<br>";
});
});
}
function getRandom(min, max) {
return Math.random() * (max - min + 1) + min;
}
google.maps.event.addDomListener(window, 'load', initialize);
function makeRandomMarkers() {
var bounds = map.getBounds();
var maxLat = bounds.getNorthEast().lat(); // 70;
var minLat = bounds.getSouthWest().lat(); // 37;
var maxLong = bounds.getNorthEast().lng(); // 50;
var minLong = bounds.getSouthWest().lng(); // -8;
for (var j = 0; j < 50; j++) {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(getRandom(minLat, maxLat),
getRandom(minLong, maxLong)),
map: map
});
markers.push(marker);
}
}
html,
body {
height: 100%;
margin: 0
}
#map_canvas {
height: 90%;
}
<script src="https://maps.googleapis.com/maps/api/js?libraries=geometry"></script>
Use the right mouse-button to draw an overlay
<br/>
<div id="numberMarkers"></div>
<div id="map_canvas"></div>

Google Maps: Markers not appearing again after toggle

I am a beginner at google maps.
I am trying to toggle google map markers based on there type.
When I unchecked the check-box the marker disappears and upon checking it again the markers do not appears back on the map.
I have tried changing setmap to setvisible in toggleGroup function but that also did not worked .
</style>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Beautiful India</title>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js"></script>
<script type="text/javascript">
//<![CDATA[
var customIcons = {
restaurant: {
icon: 'http://labs.google.com/ridefinder/images/mm_20_blue.png'
},
bar: {
icon: 'http://labs.google.com/ridefinder/images/mm_20_red.png'
}
};
function load() {
var map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(47.6145, -122.3418),
zoom: 13,
mapTypeId: 'roadmap'
});
var infoWindow = new google.maps.InfoWindow;
// Change this depending on the name of your PHP file
downloadUrl("parsingxml.php", function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var name = markers[i].getAttribute("name");
var address = markers[i].getAttribute("address");
var type = markers[i].getAttribute("type");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var html = "<b>" + name + "</b> <br/>" + address;
html = "<div style=\"position: relative; float: left; width: 225px; height: 80px; border: 0px coral solid;\">" + html + "</div>";
var icon = customIcons[type] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
icon: icon.icon
});
markerGroups[type].push(marker);
bindInfoWindow(marker, map, infoWindow, html);
}
});
}
function bindInfoWindow(marker, map, infoWindow, html) {
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(html);
infoWindow.open(map, marker);
});
}
var markerGroups = { "bar": [], "restaurant": [] };
function toggleGroup(type) {
for (var i = 0; i < markerGroups[type].length; i++) {
var marker = markerGroups[type][i];
if (marker.getMap()==null) {
marker.setVisible(true);
} else {
marker.setVisible(false);
}
}
}
function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function doNothing() {}
//]]>
</script>
</head>
<body onload="load()">
<div id="panel">
<input type="checkbox" id="bar" onclick="toggleGroup('bar')"CHECKED/>
bar
<input type="checkbox" id="bar" onclick="toggleGroup('restaurant')"CHECKED/>
restaurant
</div>
<div id="map" </div>
</body>
</html>
Your issue:
You are mixing 2 different things here: getMap() and getVisible().
How to use:
To render a marker on the map, use:
marker.setMap(map); // where "map" is your map instance
To remove a marker from the map:
marker.setMap(null);
To show a hidden marker:
marker.setVisible(true);
To hide a marker:
marker.setVisible(false);
How to fix:
You should adapt your toggleGroup function accordingly.
Details:
marker.setMap(null);
marker.setVisible(true); // marker will not be shown since it's not on the map anymore

Make geocoding map zoom on scroll

I am looking at two different geocode examples I found and I am looking to get the best of both features. I have not had much experience with geocoding and I find the google docs hard to follow
This one does everything I want except scroll in when the user uses the mouse wheel. http://jsfiddle.net/Ep7Rr/
I would like this one if I could get the marker to move as the user drags the map like in the first one.http://jsfiddle.net/AjeTc/
I know there are different ways such as new GMap2 and new google.maps.Geocoder
The first one works with this code
<script>
function load() {
if (GBrowserIsCompatible()){
var map = new GMap2(document.getElementById("map"));
map.addControl(new GSmallMapControl());
map.addControl(new GMapTypeControl());
var center = new GLatLng(54.18173, -6.35284);
map.setCenter(center, 15);
geocoder = new GClientGeocoder();
var marker = new GMarker(center, {draggable: true});
map.addOverlay(marker);
document.getElementById("lat").innerHTML = center.lat().toFixed(5);
document.getElementById("lng").innerHTML = center.lng().toFixed(5);
GEvent.addListener(marker, "dragend", function(){
var point = marker.getPoint();
map.panTo(point);
document.getElementById("lat").innerHTML = point.lat().toFixed(5);
document.getElementById("lng").innerHTML = point.lng().toFixed(5);
}); /*END GEvent.addListener(marker, "dragend", function(){*/
GEvent.addListener(map, "moveend", function() {
map.clearOverlays();
var center = map.getCenter();
var marker = new GMarker(center, {draggable: true});
map.addOverlay(marker);
document.getElementById("lat").innerHTML = center.lat().toFixed(5);
document.getElementById("lng").innerHTML = center.lng().toFixed(5);
GEvent.addListener(marker, "dragend", function() {
var point =marker.getPoint();
map.panTo(point);
document.getElementById("lat").innerHTML = point.lat().toFixed(5);
document.getElementById("lng").innerHTML = point.lng().toFixed(5);
}); /*END GEvent.addListener(marker, "dragend", function() {*/
}); /*END GEvent.addListener(map, "moveend", function() {*/
} /*END if (GBrowserIsCompatible()){*/
} /*END function load*/
And the second uses this
<script type="text/javascript">
function showAddress() {
var map = new GMap2(document.getElementById("map"));
var address = document.getElementById('fullAddress').value;
return false;
} /*END function showAddress*/
var geocoder = new google.maps.Geocoder();
function geocodePosition(pos) {
geocoder.geocode({
latLng: pos
}, function(responses) {
if (responses && responses.length > 0) {
updateMarkerAddress(responses[0].formatted_address);
} else {
updateMarkerAddress('Cannot determine address at this location.');
}
});
}
function updateMarkerStatus(str) {
document.getElementById('markerStatus').innerHTML = str;
}
function updateMarkerPosition(latLng) {
document.getElementById('info').innerHTML = [
latLng.lat(),
latLng.lng()
].join(', ');
}
function updateMarkerAddress(str) {
document.getElementById('address').innerHTML = str;
}
function initialize() {
var latLng = new google.maps.LatLng(54.18173, -6.35284);
var map = new google.maps.Map(document.getElementById('mapCanvas'), {
zoom: 8,
center: latLng,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var marker = new google.maps.Marker({
position: latLng,
title: 'Point A',
map: map,
draggable: true
});
// Update current position info.
updateMarkerPosition(latLng);
geocodePosition(latLng);
// Add dragging event listeners.
google.maps.event.addListener(marker, 'dragstart', function() {
updateMarkerAddress('Dragging...');
});
google.maps.event.addListener(marker, 'drag', function() {
updateMarkerStatus('Dragging...');
updateMarkerPosition(marker.getPosition());
});
google.maps.event.addListener(marker, 'dragend', function() {
updateMarkerStatus('Drag ended');
geocodePosition(marker.getPosition());
});
}
// Onload handler to fire off the app.
google.maps.event.addDomListener(window, 'load', initialize);
</script>
Catch the event when the map is dragged.
Update the position of the marker by getting the map center
Geocode the position of the marker
google.maps.event.addListener(map, 'dragend', function() {
updateMarkerStatus('Drag ended');
marker.setPosition(map.getCenter());
geocodePosition(marker.getPosition());
});
like this : http://jsfiddle.net/ZYV9N/

Not able to register click listener on a marker in Google Maps v3

Actually i am migrating from Maps v2 to v3. But i am facing a really weird error.
Here is my code
function createMarker(arrayPos,title,posn) {
var size = {width:15,height:15};
var iconSize = new google.maps.Size(size.width,size.height);
var iconAnchor = new google.maps.Point(9, 34);
var marker = new google.maps.Marker({
icon: new google.maps.MarkerImage("my.png",iconSize,null,iconAnchor),
title: title,
animation: google.maps.Animation.DROP,
position: posn
});
marker.html = getMarkerHtml(arrayPos);
var infowindow = new google.maps.InfoWindow();
infowindow.setContent(marker.html);
infowindow.open(map,marker);
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(marker.html);
infowindow.open(map,marker);
});
return marker;
}
In this i was experimenting opening the infowindow as soon as markers are added and also on the click listener. In this all the infowindow opens but the listerner is not registered on the first marker always. Any pointers in this?
I have modified your code as following and it works. Would you check whether it solves your issue?
In order to simulate a marker click you should add: google.maps.event.trigger(marker, 'click');
function createMarker(arrayPos,title,posn) {
var size = {width:15,height:15};
var iconSize = new google.maps.Size(size.width,size.height);
var iconAnchor = new google.maps.Point(9, 34);
var marker = new google.maps.Marker({
icon: new google.maps.MarkerImage("my.png",iconSize,null,iconAnchor),
title: title,
animation: google.maps.Animation.DROP,
position: posn
});
//marker.html = getMarkerHtml(arrayPos);
var infowindow = new google.maps.InfoWindow();
//infowindow.setContent(marker.html);
//infowindow.open(map,marker);
var markersHTML = getMarkerHtml(arrayPos);
google.maps.event.addListener(marker, 'click', (function(marker, markersHTML) {
return function() {
infowindow.setContent(markersHTML);
infowindow.open(map, marker);
}
})(marker, markersHTML));
return marker;
}
Example:
<!doctype html>
<html lang="en">
<head>
<title>Google Maps</title>
<script src="http://code.jquery.com/jquery-1.8.2.min.js"></script>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?v=3&sensor=false&language=en"> </script>
<script type="text/javascript">
var cityList = [
['Chicago', 41.850033, -87.6500523, 1],
['Illinois', 40.797177,-89.406738, 2]
],
demoCenter = new google.maps.LatLng(41,-87),
map;
function initialize()
{
map = new google.maps.Map(document.getElementById('map_canvas'), {
zoom: 7,
center: demoCenter,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
}
function addMarkers()
{
var marker,
i,
infowindow = new google.maps.InfoWindow();
for (i = 0; i < cityList.length; i++)
{
marker = new google.maps.Marker({
position: new google.maps.LatLng(cityList[i][1], cityList[i][2]),
map: map,
title: cityList[i][0]
});
var markersHTML = ["<div>",cityList[i][0],"</div>"].join("");
google.maps.event.addListener(marker, 'click', (function(marker, markersHTML) {
return function() {
infowindow.setContent(markersHTML);
infowindow.open(map, marker);
}
})(marker, markersHTML));
}
}
$(document).ready(function() {
initialize();
});
$(document).on('click', '.add-markers', function(e) {
e.preventDefault();
addMarkers();
});
</script>
</head>
<body>
<div id="basic-map">
<div id="map_canvas" style="height:350px;"></div>
Add Some Markers
</div>
</body>
</html>
I hope this helps.