How do i access all my google maps markers - javascript

I am not seeing it i'll think if one of you looks at it can immediately tell me what i have to do. Now i resize my marker but it only takes the last marker of the array.
here the code I'll loop trough the array of object markers:
var locations = [
[{id: 1, lat: 51.523229192354066, lng: 5.139241042480535, content: 'Title A'}],
[{id: 2, lat: 51.52309568310267, lng: 5.139251771316594, content: 'Title B'}],
[{id: 3, lat: 51.5229888754197, lng: 5.139434161529607, content: 'Title C'}],
[{id: 4, lat: 51.52284868995566, lng: 5.139487805709905, content: 'Title D'}],
[{id: 5, lat: 51.522715179588666, lng: 5.139670195922918, content: 'Title E'}],
[{id: 6, lat: 51.52258166883027, lng: 5.1397989419556325, content: 'Title F'}],
[{id: 7, lat: 51.52242813097418, lng: 5.139927687988347, content: 'Title G'}],
[{id: 8, lat: 51.52227793039666, lng: 5.139927687988347, content: 'Title H'}],
[{id: 9, lat: 51.522625059869696, lng: 5.138688507423467, content: 'Title I'}]
];
for (i = 0; i < locations.length; i++) {
var myLatLng = {lat: locations[i][0].lat, lng: locations[i][0].lng};
marker = new google.maps.Marker({
position: myLatLng,
icon: icon1,
map: map
});
map.addListener('zoom_changed', function() {
if (map.getZoom() === 17) {
marker.icon.scaledSize = new google.maps.Size(32, 32);
marker.icon.size = new google.maps.Size(32, 32);
marker.setMap(map);
}
if (map.getZoom() === 18) {
console.log(marker[i]);
marker.icon.scaledSize = new google.maps.Size(90, 90);
marker.icon.size = new google.maps.Size(90, 90);
marker.setMap(map);
}
});
If i try to access marker[i].icon it is undefined. Please can somebody help me out to use size ALL the markers.
Here is a fiddle for a better view zoom in and out to see what happens only one marker change in size:
https://jsfiddle.net/sylvanR/a8z0yyeq/10/

The problem is this: you're looping over all your markers, adding a new event listener for the map's zoom_changed event. In each of those event listeners, you're referring to the variable marker. This event listener function doesn't get executed at the moment you define it, it only happens when the zoom changes obviously. So at that point, the variable marker will equal whatever it was at the very last iteration of your for loop.
Instead you need to change how you setup this event listener, something like this:
for (i = 0; i < locations.length; i++) {
var myLatLng = {lat: locations[i][0].lat, lng: locations[i][0].lng};
marker = new google.maps.Marker({
position: myLatLng,
icon: icon1,
map: map
});
setMarkerSize(marker);
}
function setMarkerSize(marker) {
var icon = marker.icon;
map.addListener('zoom_changed', function() {
if (map.getZoom() === 16) {
icon.scaledSize = new google.maps.Size(15, 15);
icon.size = new google.maps.Size(15, 15);
marker.setIcon(icon);
console.log(marker.icon.size);
}
if (map.getZoom() === 17) {
icon.scaledSize = new google.maps.Size(32, 32);
icon.size = new google.maps.Size(32, 32);
marker.setIcon(icon);
console.log(marker.icon.size);
}
if (map.getZoom() === 18) {
icon.scaledSize = new google.maps.Size(90, 90);
icon.size = new google.maps.Size(90, 90);
marker.setIcon(icon);
console.log(marker.icon.size);
}
});
}
In this case, marker inside the setMarkerSize function is a local variable that will be different each time you call the function.

Related

How to set individual Google Maps Marker Icons

I know this question was asked more often. But for my code, unfortunately, none of the answers work for me. I have the following Google Maps code and would like to set my own google maps marker icon.
For this I have tried the following code. Unfortunately without success.
<script type="text/javascript" src="//maps.googleapis.com/maps/api/js?
key=key"></script>
<div id="map_canvas"></div>
<script>
var locations = [
['title',51.0, 11.0, 'https://www.domain.de/, 4],
['title',51.0, 11.0, 'https://www.domain.de/, 4],
['title',51.0, 11.0, 'https://www.domain.de/, 4],
['title',51.0, 11.0, 'https://www.domain.de/, 4],
['title',51.0, 11.0, 'https://www.domain.de/, 4],
['title',51.0, 11.0, 'https://www.domain.de/, 4]
];
var map;
var markers = [];
function init(){
map = new google.maps.Map(document.getElementById('map_canvas'), {
zoom: 7,
center: new google.maps.LatLng(51.5151, 10.4545),
mapTypeId: google.maps.MapTypeId.ROADMAP,
styles:
[
]
});
function setMarkers(map) {
var image = {
url: 'marker-path/marker.jpg',
size: new google.maps.Size(20, 32),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(0, 32)
};
var shape = {
coords: [1, 1, 1, 20, 18, 20, 18, 1],
type: 'poly'
};
var num_markers = locations.length;
for (var i = 0; i < num_markers; i++) {
markers[i] = new google.maps.Marker({
position: {lat:locations[i][1], lng:locations[i][2]},
map: map,
icon: image,
html: locations[i][0],
id: i,
});
google.maps.event.addListener(markers[i], 'click', function(){
var infowindow = new google.maps.InfoWindow({
id: this.id,
content:this.html,
position:this.getPosition()
});
google.maps.event.addListenerOnce(infowindow, 'closeclick', function(){
markers[this.id].setVisible(true);
});
this.setVisible(false);
infowindow.open(map);
});
}
}}
init();
</script>
Unfortunately, no marker is displayed. Where is the problem?
First of all, make sure that (1) the path to your image is correct, and (2) your image's size is in fact 20 x 32 (otherwise change Size accordingly).
Your code snippet has lots of issues, and I have amended it as follows to be able to reproduce it from my side:
<script>
var locations = [
['title', 41.38879, 2.15899, 'https://www.domain.de/', 4],
['title', 48.85341, 2.3488, 'https://www.domain.de/', 4],
['title', 52.52437, 13.41053, 'https://www.domain.de/', 4]
];
var map;
var markers = [];
function init() {
map = new google.maps.Map(document.getElementById('map_canvas'), {
zoom: 5,
center: new google.maps.LatLng(51.5151, 10.4545),
mapTypeId: google.maps.MapTypeId.ROADMAP,
styles: []
});
setMarkers(map);
}
function setMarkers(map) {
var image = {
url: 'maker-path/maker.jpg',
size: new google.maps.Size(20, 32),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(0, 32)
};
var num_markers = locations.length;
for (var i = 0; i < num_markers; i++) {
markers[i] = new google.maps.Marker({
position: { lat: locations[i][1], lng: locations[i][2] },
map: map,
icon: image,
html: locations[i][0],
id: i
});
google.maps.event.addListener(markers[i], 'click', function() {
var infowindow = new google.maps.InfoWindow({
id: this.id,
content: this.html,
position: this.getPosition()
});
google.maps.event.addListenerOnce(infowindow, 'closeclick', function() {
markers[this.id].setVisible(true);
});
this.setVisible(false);
infowindow.open(map);
});
}
}
</script>
You can also test this first by replacing "maker-path/maker.jpg" with e.g. https://developers.google.com/maps/documentation/javascript/examples/full/images/beachflag.png.
You'll see how the icon from Google's documentation is indeed displayed.
If your own icon is not, then that means that you need to double check pointers (1) and/or (2) I stated above.
Hope this helps!

How to add multiple markers in Gmap3?

I am trying to add multiple marker in gmap3. but it can't work.
If anybody any idea how to add multiple location in gmap3 API.
var contactmap = {
lat: 24.091328,
lng: 38.037067
};
$('#tm-map')
.gmap3({
zoom: 13,
center: contactmap,
scrollwheel: false,
mapTypeId: "shadeOfGrey",
mapTypeControlOptions: {
mapTypeIds: [google.maps.MapTypeId.ROADMAP, "shadeOfGrey"]
}
})
.marker({
position: contactmap,
icon: 'assets/img/map-marker.gif'
})
This code is view only one marker. So how can I add multiple marker in Map?.
So finally I found the Right solution with myself so thanks to support me.
var locations = [
['Yanbu Saudi Arabia', 24.091328, 38.037067, 1],
['Yanbu Saudi Arabia', 24.005421, 38.197395, 2]
];
var map = new google.maps.Map(document.getElementById('tm-map'), {
zoom: 10,
center: new google.maps.LatLng(24.005421, 38.197395),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow();
var marker, i;
var markers = [];
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
});
markers.push(marker);
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
}
console.log(markers[0]);
create an array of markers and then push each new marker object into that array and finally pass array into your marker()
follow this github response https://github.com/jbdemonte/gmap3/issues/123
for any future problems refer to their github page.
// this is how you create array
var multiadress = [{latLng:[1,2],content:"abcd"},{latLng:[3,4],content:"pqr"},{latLng:[6,7],content:"kbc"}]
var markers = [];
$.each(multiadress, function(key, val){
var latLng = val.latLng
markers.push({
position: latLng,
content: val.content
});
});
var contactmap = {
lat: 24.091328,
lng: 38.037067
};
$('#tm-map')
.gmap3({
zoom: 13,
center: contactmap,
scrollwheel: false,
mapTypeId: "shadeOfGrey",
mapTypeControlOptions: {
mapTypeIds: [google.maps.MapTypeId.ROADMAP, "shadeOfGrey"]
}
})
.marker(markers)
accept answer if it helps you.
You can pass a markerList:
var markers = [
{ lat: 37.772, lng: -122.214 },
{ lat: 21.291, lng: -157.821 },
{ lat: -18.142, lng: 178.431 },
{ lat: -27.467, lng: 153.027 }
];
function markerSetup(markers){
var mapOptions = {
center: new google.maps.LatLng(markers[0].lat, markers[0].lng),
zoom: 10,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var icon = {
url: "../Content/Images/Car.png", // url
scaledSize: new google.maps.Size(50, 60), // scaled size
origin: new google.maps.Point(0, 0), // origin
anchor: new google.maps.Point(0, 0) // anchor
};
// alert(markers[0].lat)
var map = new google.maps.Map(document.getElementById("dvMap"), mapOptions);
var trafficLayer = new google.maps.TrafficLayer();
trafficLayer.setMap(map);
// map.setMap(trafficLayer);
var infoWindow = new google.maps.InfoWindow();
var lat_lng = new Array();
var latlngbounds = new google.maps.LatLngBounds();
for (i = 0; i < markers.length; i++) {
var data = markers[i]
var myLatlng = new google.maps.LatLng(data.lat, data.lng);
lat_lng.push(myLatlng);
var marker = new google.maps.Marker({
position: myLatlng,
icon: icon,
map: map,
title: data.title
});
latlngbounds.extend(marker.position);
(function (marker, data) {
google.maps.event.addListener(marker, "click", function (e) {
infoWindow.setContent(data.description);
infoWindow.open(map, marker);
});
})(marker, data);
}
map.setCenter(latlngbounds.getCenter());
map.fitBounds(latlngbounds);
map.setZoom(12)
});
}
It's workable code. Hope it's help you.
I do it like this:
$('#tm-map')
.gmap3({
zoom: 13,
center: contactmap,
scrollwheel: false,
mapTypeId: "shadeOfGrey",
mapTypeControlOptions: {
mapTypeIds: [google.maps.MapTypeId.ROADMAP, "shadeOfGrey"]
}
})
.marker(
{position: [51.552970, 8.560290], icon: 'assets/img/map-marker.gif'},
{position: [51.552970, 8.560290], icon: 'assets/img/map-marker.gif'},
{position: [51.552970, 8.560290], icon: 'assets/img/map-marker.gif'},
{position: [51.552970, 8.560290], icon: 'assets/img/map-marker.gif'}
)

Add marker with label in google map's every end of polyline

I've multiple polylines, I want a marker on every end and start of polyline with a label, I am tracking bike movement, I am getting the polyline but i need to display the time on poly line or on the end point, if i can show the time in the polyline it would be great. I am developing a tracking system, i am getting the lat long, of start and end points i am also abple to draw polylines, i want to display time on the polyline or at least display a marker on every end and show the time... below is my code
var bikearray = [];
$('#searchbtn').on('click', function() {
$.ajax({
url:'http://metrobikes.in/api/a2b-bike-movement-on-map',
method:"GET",
data : {
start_Date : "2017-12-11",
end_date : "2018-01-24",
bike_number : "KA-51-D-6109"
},
}).done(function(data){
bikearray = data.result.data;
initMap();
});
});
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 13,
center: new google.maps.LatLng(12.98966, 77.653637),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var lineSymbol = {
path: google.maps.SymbolPath.FORWARD_CLOSED_ARROW
};
for(i = 0; i < bikearray.length; i++){
var from_lat = parseFloat(bikearray[i].from_lat);
var from_long = parseFloat(bikearray[i].from_long);
var to_lat = parseFloat(bikearray[i].to_lat);
var to_long =parseFloat(bikearray[i].to_long);
var linecolor = bikearray[i].colour;
console.log(bikearray[i].from_lat);
var bikePath = new google.maps.Polyline({
path: [
{lat: from_lat, lng: from_long},
{lat: to_lat, lng: to_long}
],
icons: [{
icon: lineSymbol,
repeat:'35px',
offset: '100%'
}],
geodesic: true,
strokeColor: linecolor,
strokeOpacity: 1.0,
strokeWeight: 2,
map: map
});
bikePath.setMap(map);
}
}
To add a marker to the beginning and end of the polyline, add a marker to the beginning point and to the ending point. To add the time in an InfoWindow on the end marker, add that as well (and trigger a click on it to open it):
for(i = 0; i < bikearray.length; i++){
var from_lat = parseFloat(bikearray[i].from_lat);
var from_long = parseFloat(bikearray[i].from_long);
var startMarker = new google.maps.Marker({
map: map,
position: {lat: from_lat, lng: from_long}
});
var to_lat = parseFloat(bikearray[i].to_lat);
var to_long =parseFloat(bikearray[i].to_long);
var endMarker = new google.maps.Marker({
map: map,
position: {lat: to_lat, lng: to_long}
});
var time = bikearray[i].time;
var infowindow = new google.maps.InfoWindow();
google.maps.event.addListener(endMarker, 'click', (function(marker, time, infowindow) {
return function(evt) {
infowindow.setContent(time);
infowindow.open(map, marker);
}})(endMarker, time, infowindow));
google.maps.event.trigger(endMarker, 'click');
var linecolor = bikearray[i].colour;
proof of concept fiddle
code snippet:
var bikearray = [{
from_lat: 12.98966,
from_long: 77.653637,
to_lat: 12.9715987,
to_long: 77.5945626,
colour: "blue",
time: "12:00"
},
{
from_lat: 13.0826802,
from_long: 80.2707184,
to_lat: 12.9922145,
to_long: 77.7159,
colour: "red",
time: "11:00"
},
]
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 13,
center: new google.maps.LatLng(12.98966, 77.653637),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var lineSymbol = {
path: google.maps.SymbolPath.FORWARD_CLOSED_ARROW
};
for (i = 0; i < bikearray.length; i++) {
var from_lat = parseFloat(bikearray[i].from_lat);
var from_long = parseFloat(bikearray[i].from_long);
var startMarker = new google.maps.Marker({
map: map,
position: {
lat: from_lat,
lng: from_long
}
});
var to_lat = parseFloat(bikearray[i].to_lat);
var to_long = parseFloat(bikearray[i].to_long);
var endMarker = new google.maps.Marker({
map: map,
position: {
lat: to_lat,
lng: to_long
}
});
var time = bikearray[i].time;
var infowindow = new google.maps.InfoWindow();
google.maps.event.addListener(endMarker, 'click', (function(marker, time, infowindow) {
return function(evt) {
infowindow.setContent(time);
infowindow.open(map, marker);
}
})(endMarker, time, infowindow));
google.maps.event.trigger(endMarker, 'click');
var linecolor = bikearray[i].colour;
console.log(bikearray[i].from_lat);
var bikePath = new google.maps.Polyline({
path: [
{
lat: from_lat,
lng: from_long
},
{
lat: to_lat,
lng: to_long
}
],
icons: [{
icon: lineSymbol,
repeat: '35px',
offset: '100%'
}],
geodesic: true,
strokeColor: linecolor,
strokeOpacity: 1.0,
strokeWeight: 2,
map: map
});
bikePath.setMap(map);
}
}
google.maps.event.addDomListener(window, "load", initMap);
html,
body,
#map {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div id="map"></div>
Looks like this was already answered in Text Within Polyline Google Maps V3
One solution would be using this library from github:
https://github.com/googlemaps/js-map-label
You could use it like this:
var labelPosition = new google.maps.LatLng(middle_lat, middle_long);
var mapLabel = new MapLabel({
text: "Your text",
position: labelPosition ,
map: map,
fontSize: 12
});
You would have to calculate the Middle-Point between the two points.

How to add event listener to Map marker[ ] array

I've got a google map implementation that drops the pins on the map using a couple function calls and a marker[ ] array.
It works great, but I can't figure out how to possibly add an onClick event or other type of event listener to the function since it doesn't have a marker variable defined explicitly.
Where would I be able to add something like this?:
google.maps.event.addListener(markers, 'click', function() {
window.location.href = this.url;};
Here is my basic map code and functions:
var pinlocations = [
['1', {lat: 30.266758, lng: -97.739080}, 12, '/establishments/1111'],
['2', {lat: 30.267178, lng: -97.739050}, 11, '/establishments/1222'],
['3', {lat: 30.267458, lng: -97.741231}, 10, '/establishments/1333'],
['4', {lat: 30.388880, lng: -97.892276}, 9, '/establishments/1444']
];
var markers = [];
var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 12,
center: {lat: 30.267178, lng: -97.739050}
});
}
function drop() {
clearMarkers();
for (var i = 0; i < pinlocations.length; i++) {
var place = pinlocations[i];
addMarkerWithTimeout(place[1], place[0], place[2], place[3], i * 200);
}
}
function addMarkerWithTimeout(position, title, zindex, url, timeout) {
window.setTimeout(function() {
markers.push(new google.maps.Marker({
position: position,
map: map,
title: title,
zIndex: zindex,
url: url,
animation: google.maps.Animation.DROP
}));
}, timeout);
}
You don't add an event to an array, you have to add it to each element within the array. You can do this with the .forEach() array method:
// Iterate the markers array
markers.forEach(function(marker){
// Set up a click event listener for each marker in the array
marker.addListener('click', function() {
window.location.href = marker.url;
});
});
Or, you could take another approach and add the event at the moment each individual marker gets created.
function addMarkerWithTimeout(position, title, zindex, url, timeout) {
window.setTimeout(function() {
markers.push(new google.maps.Marker({
position: position,
map: map,
title: title,
zIndex: zindex,
url: url,
animation: google.maps.Animation.DROP
}).addListener('click', function() {
window.location.href = this.url;
});
}, timeout);
}

google map spiderfier cluster

Question about spiderfier cluster, I managed to make it work with markerClusterer but is there a way to auto spiderfied it when you zoomin so it won't show just 1 marker when map is zoomed?
Say if you hit maxZoom level of 11 then it should automatically spiderfied the markers.
Here's my spiderfier options:
var oms = new OverlappingMarkerSpiderfier(map, {keepSpiderfied : true, markersWontMove : false, circleSpiralSwitchover: 5});
Thanks,
(function(){
var gm = google.maps;
var config = {
el: 'map',
lat: 37.4419,
lon: -122.1419,
zoom: 15,
minZoom: 15,
type: google.maps.MapTypeId.ROADMAP
};
var spiderConfig = {
keepSpiderfied: true,
event: 'mouseover'
};
// A list of Markers with the same location
var data = [
{lat: 37.4419, lon: -122.1419, title: 'location 1'},
{lat: 37.4419, lon: -122.1419, title: 'location 2'},
{lat: 37.4419, lon: -122.1419, title: 'Marker same location 3'},
{lat: 37.4419, lon: -122.1419, title: 'Marker same location 4'},
{lat: 37.4419, lon: -122.1419, title: 'Marker same location 5'},
{lat: 37.4419, lon: -122.1419, title: 'Marker same location 6'},
{lat: 37.4419, lon: -122.1419, title: 'Marker same location 7'},
{lat: 37.4419, lon: -122.1419, title: 'Marker same location 8'},
{lat: 37.4419, lon: -122.1419, title: 'Marker same location 9'}
];
function initialize() {
var map = new gm.Map(document.getElementById(config.el), {
zoom: config.zoom,
center: new gm.LatLng(config.lat, config.lon),
mapTypeId: config.type
});
var markerSpiderfier = new OverlappingMarkerSpiderfier(map, spiderConfig);
var markers = [];
for (var x in data) {
var loc = new gm.LatLng(data[x].lat, data[x].lon);
var marker = new gm.Marker({
position: loc,
title: data[x].title,
map: map
});
marker.desc = data[x].title;
markers.push(marker); // Saving Markers
markerSpiderfier.addMarker(marker); // Adds the Marker to OverlappingMarkerSpiderfier
}
var iw = new gm.InfoWindow();
markerSpiderfier.addListener('click', function(marker, e) {
iw.setContent(marker.title);
iw.open(map, marker);
});
markerSpiderfier.addListener('spiderfy', function(markers) {
iw.close();
});
var markerCluster = new MarkerClusterer(map, markers);
markerCluster.setMaxZoom(config.minZoom);
}
gm.event.addDomListener(window, 'load', initialize);
})();

Categories