JS Fiddle:
http://jsfiddle.net/megatimes/NVDLf/7/
I have a map which is creating multiple markers from an array.
Below the map are some links which, when clicked, I'd like to cause the map to pan to its respective marker, and open the info window.
Given that I don't want to generate the links themselves as part of the loop that creates the markers, how can I do this?
I'm fairly certain this is a scope issue since the links below the map each open the last item in the locations array but I can't seem to figure out how to get around it.
Thanks
var locations = [
[
"Location 1",
"215 West Girard Avenue 19123",
"39.9695601",
"-75.1395161"
],
[
"Location 2",
"5360 Old York Road 19141",
"40.034038",
"-75.145223"
],
[
"Location 3",
"1350 W Girard Avenue 19123",
"39.9713524",
"-75.1590360"
]
];
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 12,
center: new google.maps.LatLng(39.9995601, -75.1395161),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow();
var marker, i;
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][2], locations[i][3]),
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
}
$(function() {
$('#locations h3 a').each(function() {
$(this).on('click', function() {
google.maps.event.trigger(marker, 'click');
})
});
});
<div id="map" style="width: 500px; height: 400px;"></div>
<div id="locations">
<h3>Location 1</h3>
<p>Arbitrary content about 1</p>
<h3>Location 2</h3>
<p>Arbitrary content about 2</p>
<h3>Location 3</h3>
<p>Arbitrary content about 3</p>
</div>
You can do something like this:
http://jsfiddle.net/6vjwd/2/embedded/result/
uses a createMarker function to associate the infowindow with the marker:
function createMarker(latlng, html)
{
var marker = new google.maps.Marker({
position: latlng,
map: map
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(html);
infowindow.open(map, marker);
});
return marker;
}
And a global array to allow them to be referenced from HTML click listeners.
The external links depend on knowing the order of the locations. Or if you want to look them up by "name" you could use an "associative" array, with the name as the index.
Indexing the markers by name:
http://jsfiddle.net/6nqj8/1/embedded/result/
I would generate the links using jQuery while generating the markers. You can store the marker object on the link object using jQuery's .data() call and add a generic click handler to those links that set the map to the marker's location.
Something kind of like this:
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][2], locations[i][3]),
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
$('#locations').append($('<a>').append('Location Name').click(function()
{
// $(this).data('marker')
}).data('marker', marker));
}
ok, this works for me. I'm adding each marker to a global variable array called markers. Then whenever a link is clicked, check which link in the array of those links it is by using the jquery .index() function, and trigger the 'click' on the corresponding marker (link 1 = marker 1, etc).
Thanks to geocodezip as well for the createMarker function which I've re-used here.
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0; padding: 0 }
#map { width: 500px; height: 400px; }
</style>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var marker, map;
var markers = [];
function initialise() {
var i;
var locations = [
[
"Location 1",
"215 West Girard Avenue 19123",
"39.9695601",
"-75.1395161"
],
[
"Location 2",
"5360 Old York Road 19141",
"40.034038",
"-75.145223"
],
[
"Location 3",
"1350 W Girard Avenue 19123",
"39.9713524",
"-75.1590360"
]
];
map = new google.maps.Map(document.getElementById('map'), {
zoom: 12,
center: new google.maps.LatLng(39.9995601, -75.1395161),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
infowindow = new google.maps.InfoWindow();
for (i = 0; i < locations.length; i++) {
markers.push(createMarker(new google.maps.LatLng(locations[i][2], locations[i][3]), locations[i][0]));
}
}
function createMarker(latlng, html)
{
var marker = new google.maps.Marker({
position: latlng,
map: map
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(html);
infowindow.open(map, marker);
});
return marker;
}
$(function() {
$('#locations h3 a').each(function() {
$(this).on('click', function() {
// find out which link in the array was clicked (1st, 2nd etc)
var intLinkClicked = $('#locations h3 a').index($(this));
google.maps.event.trigger(markers[intLinkClicked], 'click');
});
});
});
google.maps.event.addDomListener(window, 'load', initialise);
</script>
</head>
<body>
<div id="locations">
<h3>Location 1</h3>
<p>Arbitrary content about 1</p>
<h3>Location 2</h3>
<p>Arbitrary content about 2</p>
<h3>Location 3</h3>
<p>Arbitrary content about 3</p>
</div>
<div id="map"></div>
</body>
</html>
Related
I know this question has been answered before, but unfortunately, all links to demos/explanation pages are dead at the moment.
I would like to use the Google Maps API V3 to plot two directions (one for driving and one for walking) on the same map. If possible, I would like to use Google's default 'directions' lines, since these look nicer than the polylines.
Does anybody know how to do this? Any help is greatly appreciated!
Here is an example that I have made in the past for this. The trick is multiple DirectionsRenderer instances.
var MAP,
DIRECTIONSRENDERER1,
DIRECTIONSRENDERER2,
USER,
PLACE1,
PLACE2;
function displayDirections1(result, status) {
DIRECTIONSRENDERER1.setDirections(result)
}
function displayDirections2(result, status) {
DIRECTIONSRENDERER2.setDirections(result)
}
function getDirections(location, displayCallback) {
//https://developers.google.com/maps/documentation/javascript/3.exp/reference#DirectionsRequest
var request = {
travelMode: google.maps.TravelMode.DRIVING,
origin: USER,
destination: location
};
//https://developers.google.com/maps/documentation/javascript/3.exp/reference#DirectionsService
var service = new google.maps.DirectionsService();
service.route(request, displayCallback);
}
//Set up the map
function initialize() {
var mapOptions = {
zoom: 6,
//I used the center of the USA
center: new google.maps.LatLng(38.8282, -98.5795)
};
//Make the map
MAP = new google.maps.Map(document.getElementById('map'), mapOptions);
DIRECTIONSRENDERER1 = new google.maps.DirectionsRenderer({
map: MAP
})
DIRECTIONSRENDERER2 = new google.maps.DirectionsRenderer({
map: MAP
})
//Make marker for User location
//NOTE: for testing, the user position is fixed
USER = new google.maps.LatLng(38.8282, -98.5795);
new google.maps.Marker({
label: 'U',
cursor: "User Location",
position: USER,
map: MAP
});
//used for this demo
document.getElementById("latitude").textContent = USER.lat();
document.getElementById("longitude").textContent = USER.lng();
//Make marker for Place1 (location is arbitrary)
PLACE1 = new google.maps.LatLng(37, -97);
new google.maps.Marker({
label: '1',
cursor: "Place 1",
position: PLACE1,
map: MAP
});
//Make marker for Place2 (location is arbitrary)
PLACE2 = new google.maps.LatLng(39, -102);
new google.maps.Marker({
label: '2',
cursor: "Place 2",
position: PLACE2,
map: MAP
});
document.getElementById("p1button").addEventListener("click", function(e) {
getDirections(PLACE1, displayDirections1);
});
document.getElementById("p2button").addEventListener("click", function(e) {
getDirections(PLACE2, displayDirections2);
});
//Trigger map redraw when dom element is resized
google.maps.event.addDomListener(window, 'resize', function() {
google.maps.event.trigger(MAP, 'resize');
});
//Preserve map perspective when after resize
google.maps.event.addListener(MAP, 'resize', function() {
var center = MAP.getCenter();
google.maps.event.addListenerOnce(MAP, 'center_changed', function() {
MAP.setCenter(center);
});
});
}
//runs the code to set up demo
initialize();
html,
body,
#map {
height: 100%;
width: 100%;
border-width: 0;
margin: 0;
padding: 0;
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<b>Your location:</b>
<br/>
<span>Latitude: </span><span id="latitude"></span>
<br/>
<span>Longitude: </span><span id="longitude"></span>
<br/>
<br/>
<button id="p1button">Directions to Place1</button>
<button id="p2button">Directions to Place2</button>
<div id="map"></div>
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>
i have this code to display a google map:
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script type="text/javascript">
function initialize() {
var mapOptions = {
zoom: 10,
center: new google.maps.LatLng(40.714364, -74.005972),
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("googlemap"), mapOptions);
var locations = [
['New York', 40.714364, -74.005972, 'http://www.google.com/intl/en_us/mapfiles/ms/micons/green-dot.png']
];
var marker, i;
var infowindow = new google.maps.InfoWindow();
google.maps.event.addListener(map, 'click', function() {
infowindow.close();
});
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map,
icon: locations[i][3]
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
}
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
<div id="googlemap" style="width: 100%; height: 500px;"></div>
Open Info Window
That's not the final code, because i want add more markers.
The problem is, that i need external links to open the info window of a marker.
For Example:
Link 1 opens the info window from marker 1
Link 2 opens the info window from marker 2
etc...
I need a link something like this:
Open Info Window One
Here is my code in jsfiddle:
http://jsfiddle.net/fJ4jG/3/
I found couple of solutions, but i don't know how to use this code together with my code.
It should work like this:
http://www.geocodezip.com/v3_MW_example_map2.html
Thanks for every help!
What that example does is it creates an array where it stores the markers. So when the markers are created, they get pushed to that markers array. When you click on the link you send an index with the function that is a reference to the marker in the array.
So JavaScript looks like this:
var markers = [];
// The array where to store the markers
function initialize() {
var mapOptions = {
zoom: 10,
center: new google.maps.LatLng(40.714364, -74.005972),
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("googlemap"), mapOptions);
var locations = [
['New York', 40.714364, -74.005972, 'http://www.google.com/intl/en_us/mapfiles/ms/micons/green-dot.png']
];
var marker, i;
var infowindow = new google.maps.InfoWindow();
google.maps.event.addListener(map, 'click', function() {
infowindow.close();
});
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map,
icon: locations[i][3]
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
// Push the marker to the 'markers' array
markers.push(marker);
}
}
google.maps.event.addDomListener(window, 'load', initialize);
// The function to trigger the marker click, 'id' is the reference index to the 'markers' array.
function myClick(id){
google.maps.event.trigger(markers[id], 'click');
}
And in your HTML a tag you add the myClick function like this:
Open Info Window
Example: http://jsfiddle.net/fJ4jG/9/
As in my example.
add a global array to save references to the google.maps.Marker objects:
var gmarkers = [];
push the markers onto that array as you create them
gmarkers.push(marker);
trigger the "click" event on the desired marker:
Open Info Window
jsfiddle
use this code i already tried it
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(locations[i][0]);
infoWindow.open(map, marker);
});
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.
There's got to be a way to add a listener to ALL MARKERS, currently I'm adding a listener to each one using a loop which feels really wrong...
This feels wrong:
google.maps.event.addListener(unique_marker_id, 'click', function(){
//do something with this marker...
});
In both Marker and MarkerWithLabel case, you might just as well use the this keyword to refer the object to which the event handler is attached:
google.maps.event.addListener(marker, 'click', function () {
// do something with this marker ...
this.setTitle('I am clicked');
});
this here is referring to the particular marker object.
You need to add the listener to each marker, but you can make it easy by e.g. defining a function like
function createMarker(pos, t) {
var marker = new google.maps.Marker({
position: pos,
map: m, // google.maps.Map
title: t
});
google.maps.event.addListener(marker, 'click', function() {
alert("I am marker " + marker.title);
});
return marker;
}
and call it appropriately:
var m1 = createMarker(new google.maps.LatLng(...), "m1");
var m2 = createMarker(new google.maps.LatLng(...), "m2");
or in a loop, etc.
If you're using GoogleMaps v3.16 or later, you can add the event handler to the whole map.data layer.
var map = new google.maps.Map(document.getElementById("map-canvas"), options);
map.data.loadGeoJson('http://yourserver.com/path/to/geojson.json');
map.data.addListener('click', function(e) {
// this - instance of the layer object, in this case - map.data
// e.feature - instance of the feature object that initiated the event
// e.latLng - the position of the event
});
see: https://developers.google.com/maps/documentation/javascript/examples/layer-data-event
I managed to do this using FusionTablesLayer. It's a bit of work setting everything up correctly, but once you're done, it's ultra-fast, even with thousands of markers.
You basically create a public table in Google Docs and query it from your webpage. The map is pre-generated on Googles' servers, which is why it performs so well.
A complete demo page:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Google Maps Demo</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
<meta charset="UTF-8">
<style type="text/css">
html, body, #map_canvas
{
margin: 0;
padding: 0;
height: 100%;
}
</style>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
function initialize()
{
var denmark = new google.maps.LatLng(56.010666, 10.936890);
map = new google.maps.Map(document.getElementById('map_canvas'), {
center: denmark,
zoom: 7,
mapTypeId: 'roadmap'
});
layer = new google.maps.FusionTablesLayer({
query: {
select: 'Coordinates',
from: '1234567'
}
});
layer.setMap(map);
google.maps.event.addListener(layer, 'click', function (event) {
alert('Hello World!'); });
}
</script>
</head>
<body onload="initialize()">
<div id="map_canvas"></div>
</body>
</html>
Check out this article for more info, "Too Many Markers!" by Luke Mahe and Chris Broadfoot from the Google Geo APIs Team.
I managed to get an answer here:
Google Maps and Their Markers
and a demo here:
http://jsfiddle.net/salman/bhSmf/
This simplest way is this:
google.maps.event.addListener(marker, 'click', function() {
var marker = this;
alert("Tite for this marker is:" + this.title);
});
To Expand on Jiri answer purley for those searching who also wish to add a custom label etc. In the spirit of Jiri post, in shorthand version:
var m1 = createMarker({lat: -25.363, lng: 131.044}, "m1", "<div id=\"content\"><div id=\"siteNotice\"></div> <h1 id=\"firstHeading\" class=\"firstHeading\">m1</h1> <div id=\"bodyContent\">Some info</div> </div>");
function createMarker(pos, t, d) {
var marker = new google.maps.Marker({
position: pos,
map: map,
title: t
});
google.maps.event.addListener(marker,"click", function() {
alert("I am marker " + marker.title);
new google.maps.InfoWindow({ content: d }).open(map, marker);
});
return marker;
}
Remove alert, just there to show the action etc. as with Jiri's info, you can add m2, m3 etc. I thought this simply finished things off.
/* Note: I have a set of data, and it is named by the variable data.
* The variable data is an array
*/
//Here I get the length of the data
var dataLength = data.length;
//Then I iterate through all my pieces of data here
//NOTICE THAT THE KEYWORD let IS SO IMPORTANT HERE
for(let markerIterator = 0; markerIterator < dataLength; markerIterator++) {
/* This creates a new google maps marker based on my data's latitude and
* longitude
*/
var marker = new google.maps.Marker({
position: { lat: data[markerIterator].latitude, lng:
data[markerIterator].longitude },
map: map
});
google.maps.event.addListener(marker, 'click', function () {
/* This will spit out the unique markerIterator value for each marker when
* clicked. It is a unique value because I defined markerIterator with the
* keyword let!
*/
console.log(markerIterator);
// Use the keyword this to refer to each unique marker, for example:
map.setCenter(this.getPosition());
});
}
What i've Done is, when adding new marker on map and before pushing it into markers = [] array, i just add listener to it marker.addListener('click', () => { // Do Something here});
Complete Code:
// Adds a marker to the map and push to the array.
function addMarker(location) {
var marker = new google.maps.Marker({
position: location,
icon: {
url: "http://maps.google.com/mapfiles/ms/icons/blue-dot.png"
},
animation: google.maps.Animation.DROP,
map: map
});
marker.addListener("click",
() => {
console.log("Marker Click Event Fired!");
});
markers.push(marker);
}
LINK i followed!
It was really hard for me to find a specific answer to my need. But this one is working now and everywhere for me!
Regards! :)
var map;
function initialize_map(locations) {
var options = {
zoom: 8,
center: new google.maps.LatLng(59.933688,30.331879),
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("map-canvas"), options);
var bounds = new google.maps.LatLngBounds();
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][lat], locations[i][lng]),
map: map,
title: locations[i][title]
});
set_event(marker);
bounds.extend(marker.position);
}
map.fitBounds(bounds);
}
function set_event(marker) {
google.maps.event.addListener(marker, 'click', function() {
// do something with this marker ...
});
}
You can do something like this:
function setMarkers(map, locations) {
var image = ['circle_orange.png','circle_blue .png'];
for (var i = 0; i < locations.length; i++) {
var stations = locations[i];
var myLatLng = new google.maps.LatLng(stations[1], stations[2]);
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
icon: image[stations[3]],
title: stations[0],
zIndex: stations[3],
optimized: false
});
var infowindow = new google.maps.InfoWindow({
content: "No data available"
});
google.maps.event.addListener(marker, 'mouseover', function() {
infowindow.setContent("We can include any station information, for example: Lat/Long: "+ stations[1]+" , "+stations[2]);
infowindow.open(map, this);
});
}
}