Related
I am trying to add MarkerClusters to my map, however my marker variable is within a function with a foreach loop used to retrieve Instagram API data, what is the best possible way to get MarkerClusters working?
I tried wrapping the initMap function around the setMarkers function, putting the markerCluster variable within the setMarkers function and within the foreach loop but it just keeps showing the markers (pictures in my case)
<script>
let coords = document.getElementById("places").innerHTML;
let parts = coords.split(",");
let finalResult = []
while (parts.length) {
let newArr = parts.splice(0, 3);
finalResult.push(newArr);
}
console.log(finalResult)
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: {
lat: 52.9,
lng: 101.2
}
});
setMarkers(map);
}
function setMarkers(map) {
finalResult.forEach((place) => {
var image = {
url: place[0],
scaledSize: new google.maps.Size(64, 64),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(32, 32)
};
var shape = {
coords: [1, 1, 1, 20, 18, 20, 18, 1],
type: 'poly'
};
var myLatlng = new google.maps.LatLng(place[1], place[2]);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
icon: image,
shape: shape
});
})
var markerCluster = new MarkerClusterer(map, marker,
{imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m'});
}
</script>
<script src="https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/markerclusterer.js">
</script>
One option is to create the MarkerClusterer inside your setMarkers function, then add the markers to it individually as you create them with the .addMarker method.
function setMarkers(map) {
var markerCluster = new MarkerClusterer(map, [], {
imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m'
});
finalResult.forEach((place) => {
var image = {
url: place[0],
};
var myLatlng = new google.maps.LatLng(place[1], place[2]);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
icon: image,
});
markerCluster.addMarker(marker);
});
proof of concept fiddle
code snippet:
let coords = document.getElementById("places").innerHTML;
let parts = coords.split(",");
let finalResult = []
while (parts.length) {
let newArr = parts.splice(0, 3);
finalResult.push(newArr);
}
console.log(finalResult)
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 3,
center: {
lat: -38,
lng: 150
}
});
setMarkers(map);
}
function setMarkers(map) {
var bounds = new google.maps.LatLngBounds();
var markerCluster = new MarkerClusterer(map, [], {
imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m'
});
finalResult.forEach((place) => {
var image = {
url: place[0],
};
var myLatlng = new google.maps.LatLng(place[1], place[2]);
bounds.extend(myLatlng);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
icon: image,
});
markerCluster.addMarker(marker);
map.fitBounds(bounds);
});
}
html,
body,
#map {
height: 100%;
margin: 0;
padding: 0;
}
<div id="map"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap"></script>
<script src="https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/markerclusterer.js"></script>
<div id="places" style="display:none">https://maps.google.com/mapfiles/ms/micons/blue.png,-31.563910,147.154312, https://maps.google.com/mapfiles/ms/micons/blue.png,-33.718234,150.363181, https://maps.google.com/mapfiles/ms/micons/blue.png,-33.727111,150.371124, https://maps.google.com/mapfiles/ms/micons/blue.png,-33.848588,151.209834,https://maps.google.com/mapfiles/ms/micons/blue.png,-33.851702,151.216968,
https://maps.google.com/mapfiles/ms/micons/blue.png,-34.671264,150.863657, https://maps.google.com/mapfiles/ms/micons/blue.png,-35.304724,148.662905, https://maps.google.com/mapfiles/ms/micons/blue.png,-36.817685,175.699196,https://maps.google.com/mapfiles/ms/micons/blue.png,-36.828611,175.790222,
https://maps.google.com/mapfiles/ms/micons/blue.png,-37.750000,145.116667, https://maps.google.com/mapfiles/ms/micons/blue.png,-37.759859,145.128708, https://maps.google.com/mapfiles/ms/micons/blue.png,-37.765015,145.133858,https://maps.google.com/mapfiles/ms/micons/blue.png,-37.770104,145.143299,
https://maps.google.com/mapfiles/ms/micons/blue.png,-37.773700,145.145187, https://maps.google.com/mapfiles/ms/micons/blue.png,-37.774785,145.137978, https://maps.google.com/mapfiles/ms/micons/blue.png,-37.819616,144.968119, https://maps.google.com/mapfiles/ms/micons/blue.png,-38.330766,144.695692,
https://maps.google.com/mapfiles/ms/micons/blue.png,-39.927193,175.053218, https://maps.google.com/mapfiles/ms/micons/blue.png,-41.330162,174.865694, https://maps.google.com/mapfiles/ms/micons/blue.png,-42.734358,147.439506, https://maps.google.com/mapfiles/ms/micons/blue.png,-42.734358,147.501315,
https://maps.google.com/mapfiles/ms/micons/blue.png,-42.735258,147.438000, https://maps.google.com/mapfiles/ms/micons/blue.png,-43.999792,170.463352,
</div>
I've been stuck on this issue for a while now and could really use some help. In a Google Map, I have a list of markers which are being treated as a markerArray, with their own custom icons. But along with displaying those markers, I would like for it to create a marker which is placed at the users geotagged location. I have tried merging the suggestions I've come across here on stack overflow, and have successfully gotten the users browser to center the map based off of geolocation, but whenever I try to add a marker outside of the standard var=locations, all of the markers disappear. I am providing my working code, which simply lacks the feature to add the "current location" marker. If anyone has any input, I'd be thrilled.
var map = null;
var markerArray = [];
function initialize() {
var myOptions = {
zoom: 13,
center: new google.maps.LatLng(40.746613, -73.990109),
mapTypeControl: false,
navigationControl: false,
streetViewControl: false,
zoomControl: false,
styles: [{featureType:"landscape",stylers:[{saturation:-100},{lightness:65},{visibility:"on"}]},{featureType:"poi",stylers:[{saturation:-100},{lightness:51},{visibility:"simplified"}]},{featureType:"road.highway",stylers:[{saturation:-100},{visibility:"simplified"}]},{featureType:"road.arterial",stylers:[{saturation:-100},{lightness:30},{visibility:"on"}]},{featureType:"road.local",stylers:[{saturation:-100},{lightness:40},{visibility:"on"}]},{featureType:"transit",stylers:[{saturation:-100},{visibility:"simplified"}]},{featureType:"administrative.province",stylers:[{visibility:"off"}]/**/},{featureType:"administrative.locality",stylers:[{visibility:"off"}]},{featureType:"administrative.neighborhood",stylers:[{visibility:"on"}]/**/},{featureType:"water",elementType:"labels",stylers:[{visibility:"on"},{lightness:-25},{saturation:-100}]},{featureType:"water",elementType:"geometry",stylers:[{hue:"#ffff00"},{lightness:-25},{saturation:-97}]}]
};
map = new google.maps.Map(document.getElementById('map'), myOptions);
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
initialLocation = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
map.setCenter(initialLocation);
});
}
google.maps.event.addListener(map, 'click', function() {
infowindow.close();
});
var locations = [
['90 West Apartment', 40.709943, -74.014430, 7, 'images/pin2.png'],
['Caffe Vita', 40.719652, -73.988411, 6, 'images/pin1.png'],
['Croxleys Ale House', 40.722480, -73.983386, 5, 'images/pin1.png'],
['Grays Papaya', 40.778291, -73.981829, 4, 'images/pin2.png'],
['The Back Room', 40.718723, -73.986913, 3, 'images/pin1.png'],
['MUD Coffee', 40.729912, -73.990678, 2, 'images/pin1.png'],
['Nurse Bettie', 40.718820, -73.986863, 1, 'pin2.png']];
for (var i = 0; i < locations.length; i++) {
createMarker(new google.maps.LatLng(locations[i][1], locations[i][2]),locations[i][0], locations[i][3], locations[i][4]);
}
mc.addMarkers(markerArray, true);
}
var infowindow = new google.maps.InfoWindow({
size: new google.maps.Size(150, 50)
});
function createMarker(latlng, myTitle, myNum, myIcon) {
var contentString = myTitle;
var marker = new google.maps.Marker({
position: latlng,
map: map,
icon: myIcon,
zIndex: Math.round(latlng.lat() * -100000) << 5,
title: myTitle
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(contentString);
infowindow.open(map, marker);
});
markerArray.push(marker);
}
window.onload = initialize;
Let's try this.
Put this in your initialize(): navigator.geolocation.getCurrentPosition(showPosition);
Then define showPosition:
var showPosition = function (position) {
var userLatLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
// Do whatever you want with userLatLng.
var marker = new google.maps.Marker({
position: userLatLng,
title: 'Your Location',
map: map
});
}
This question already has answers here:
Google Maps JS API v3 - Simple Multiple Marker Example
(15 answers)
Closed 8 years ago.
Like many other people I'm finding identical values within my info windows. Alas, I've been using other posts in an attempt to troubleshoot. No luck.
Issue: Each of my infowindows shows the same values. Sigh.
Any help would be appreciated.
var map;
function initialize() {
var markers = [];
var mapOptions = {
zoom: 4,
scrollwheel: false,
streetViewControl: true,
panControl: true,
zoomControl: true,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.LARGE
// position: google.maps.ControlPosition.LEFT_CENTER
},
center: new google.maps.LatLng(-25.898854, 134.091377)
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
setMarkers(map, beaches);
infowindow = new google.maps.InfoWindow({
content: "Loading..."
});
var input = /** #type {HTMLInputElement} */(
document.getElementById('pac-input'));
map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
var searchBox = new google.maps.places.SearchBox(
/** #type {HTMLInputElement} */(input));
google.maps.event.addListener(searchBox, 'places_changed', function() {
var places = searchBox.getPlaces();
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: 'assets/img/icon_pin.png',
//size: new google.maps.Size(40, 52),
//origin: new google.maps.Point(0, 0),
//anchor: new google.maps.Point(26, 20)
};
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);
});
}
var beaches = [
['Auburn', -33.847113, 151.04485, 1, '100', 'Parramatta', 'Road', 'Auburn', 'NSW', '2144', '02 7837 9800', '06:00 - 22:00', '06:00 - 22:00'],
['Balgowlah Platinum', -33.79284, 151.26376, 2, 'Shop 67, 197-215', 'Condamine', 'Street', 'Balgowlah', 'NSW', '2093', '1300 55 77 99', '06:00 - 21:30', '06:00 - 21:30'],
['Bankstown', -33.931208, 151.02895, 3, 'Unit 1-2, 9', 'Chapel', 'Street', 'South Bankstown', 'NSW', '2200', '02 8707 4700', '06:00 - 22:00', '06:00 - 22:00']
['Bayside', -37.954768, 145.03128, 4, '241 - 245', 'Bay', 'Road', 'Highett', 'VIC', '3190', '03 9559 7400', '06:00 - 22:00', '06:00 - 22:00']
];
function setMarkers(map, locations) {
var image = {
url: 'assets/img/icon_pin.png',
size: new google.maps.Size(40, 52),
origin: new google.maps.Point(0,0),
anchor: new google.maps.Point(26, 20)
};
var shape = {
coord: [1, 1, 1, 52, 40, 52, 40 , 1],
type: 'poly'
};
for (var i = 0; i < locations.length; i++) {
var beach = locations[i];
var myLatLng = new google.maps.LatLng(beach[1], beach[2]);
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
icon: image,
shape: shape
});
var contentString = '<div class="siteNotice"><h4>'+beach[0]+'</h4><p>'+beach[4]+' '+beach[5]+' '+beach[6]+' '+beach[7]+', '+beach[8]+', '+beach[9]+'</p><p><strong>Contact:</strong> '+beach[10]+'</p><p><strong>Opening Hours:</strong><br><span>Monday:</span> '+beach[11]+'<br><span>Tuesday:</span> '+beach[11]+'<br><span>Wednesday:</span> '+beach[11]+'<br><span>Thursday</span>: '+beach[11]+'<br><span>Friday:</span> '+beach[11]+'<br><span>Saturday</span>: '+beach[11]+'<br><span>Sunday:</span> '+beach[11]+'</p></div>';
google.maps.event.addListener(marker, "click", function () {
infowindow.setContent(contentString);
infowindow.open(map, this);
});
}
}
google.maps.event.addDomListener(window, 'load', initialize);
I had to create an array of info markers to hold the data.
var markers = [];
function addMapLocation(map, lat, long, title, message) {
var locationLatLong = new google.maps.LatLng(lat, long);
var locationMarker = new google.maps.Marker({ position: locationLatLong, map: map, title: title.trim() });
attachMessage(locationMarker, message);
markers.push(locationMarker);
}
function attachMessage(marker, message) {
var locationInfo = new google.maps.InfoWindow({ content: message });
google.maps.event.addListener(marker, 'click', function () { locationInfo.open(marker.get('map'), marker); });
}
I need to display multiple markers in single Google Map
I tried to place code,
<link href="http://code.google.com/apis/maps/documentation/javascript/examples/default.css" rel="stylesheet" type="text/css" />
<script src="http://maps.google.com/maps?file=api&v=2&key=my_key" type="text/javascript"></script>
<script type="text/javascript">
function initialize() {
latLngs = [
new google.maps.LatLng(44.3118328, -79.5549532),
new google.maps.LatLng(44.3118325, -80.5549533),
new google.maps.LatLng(44.3118326, -81.5549534),
new google.maps.LatLng(44.3118327, -82.5549535)
];
var latlng = new google.maps.LatLng(44.3118328, -79.5549532);
myOptions = {
zoom: 15,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
var contentString = '<div id="mapinfowindow">'+'1970 Thompson St <br> Innisfil' + '<br>' + '$329,900'
+'<br><br>View Brochure</div>';
var infowindow = new google.maps.InfoWindow({
content: contentString,
});
var image = new google.maps.MarkerImage(
'images/marker.png',
new google.maps.Size(50,50),
new google.maps.Point(0,0),
new google.maps.Point(25,50)
);
var shadow = new google.maps.MarkerImage(
'images/markershadow.png',
new google.maps.Size(78,50),
new google.maps.Point(0,0),
new google.maps.Point(25,50)
);
var shape = {
coord: [28,3,32,4,35,5,37,6,38,7,39,8,40,9,42,10,42,11,43,12,44,13,44,14,44,15,45,16,45,17,45,18,45,19,45,20,45,21,45,22,45,23,44,24,44,25,44,26,43,27,43,28,42,29,41,30,41,31,40,32,39,33,39,34,38,35,37,36,36,37,35,38,34,39,33,40,32,41,31,42,30,43,29,44,28,45,26,46,24,47,24,47,22,46,21,45,19,44,18,43,17,42,16,41,15,40,14,39,13,38,12,37,12,36,11,35,10,34,9,33,9,32,8,31,7,30,7,29,6,28,5,27,5,26,4,25,4,24,4,23,4,22,3,21,3,20,3,19,3,18,4,17,4,16,4,15,4,14,5,13,6,12,6,11,7,10,8,9,9,8,10,7,12,6,14,5,16,4,20,3,28,3],
type: 'poly'
};
var markers = new Array(latLngs.length);
for (var i = 0; i < markers.length; i++) {
markers[i] = new google.maps.Marker({
position: latLngs[i],
title:"Marker "+i,
icon: image,
shadow: shadow,
map: map,
shape: shape
});
markers[i].setMap(map);
}
for (var i2 = 0; i2 < markers.length; i2++) {
google.maps.event.addListener(markers[i2], 'click', function() {
infowindow.open(map,markers[i2]);
});
}
}
</script>
<div id="map_canvas" style="width: 691px; height: 466px; overflow:hidden;" class="bdr-grey"> </div>
This is giving me javascript error google.maps.MapTypeId undefined
and I also need to implement multiple markers in this.
So please help me to do this..
Thanks for your time for me..
The problem is that you are embedding the Google Maps API v2 (http://maps.google.com/maps?file=api&v=2&key=my_key), but you are using methods and objects of the Google Maps API v3. As the rest of your code is for Google Maps v3, try to call the Google Maps API like this:
<script type="text/javascript"
src="https://maps.google.com/maps/api/js?sensor=set_to_true_or_false">
<script type="text/javascript" language="javascript">
window.onload = function () {
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else {// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET", "StoreLocations.xml", false);
xmlhttp.send();
xmlDoc = xmlhttp.responseXML;
var x = xmlDoc.getElementsByTagName("CityName");
var mapOptions = {
center: new google.maps.LatLng(39.8634242, -98.18818149999998),
zoom: 3,
mapTypeId: google.maps.MapTypeId.ROADMAP
// marker:true
};
var infoWindow = new google.maps.InfoWindow();
var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
for (i = 0; i < x.length; i++) {
var latitudetest = x[i].getElementsByTagName("latitude")[0].childNodes[0].nodeValue;
var longitudetest = x[i].getElementsByTagName("longitude")[0].childNodes[0].nodeValue;
var data = '<div style="min-width:175px;text-align:left; min-height:80px;color:#000000;font-family:arial,sans-serif;font-style:normal; font-size:13px;">' + '<span style="font-weight:bold;font-size:13px;color:#000000;font-family:arial,sans-serif;font-style:normal; ">' + '1-800 Car Cash of' + ' ' + x[i].getElementsByTagName("storename")[0].childNodes[0].nodeValue + '</span>' + '<br/>' + x[i].getElementsByTagName("address")[0].childNodes[0].nodeValue + '<br/>' + x[i].getElementsByTagName("name")[0].childNodes[0].nodeValue + ' ' + x[i].getElementsByTagName("zipcode")[0].childNodes[0].nodeValue + '<br/>' + x[i].getElementsByTagName("phoneno")[0].childNodes[0].nodeValue + '<br/>' + '<div style="padding-top:6px;">' + '' + "Get Directions" + '' + '</div>' + '</div>';
var myLatlng = new google.maps.LatLng(latitudetest, longitudetest);
var bluePin = new google.maps.MarkerImage('http://maps.google.com/mapfiles/ms/micons/blue-dot.png',
new google.maps.Size(32, 32),
new google.maps.Point(0, 0),
new google.maps.Point(14, 35));
var pinShadow = new google.maps.MarkerImage('http://maps.google.com/mapfiles/ms/micons/msmarker.shadow.png',
new google.maps.Size(59, 32),
new google.maps.Point(0, 0),
new google.maps.Point(14, 35));
var marker = new google.maps.Marker({
position: myLatlng,
icon: bluePin,
shadow: pinShadow,
map: map,
title: x[i].getElementsByTagName("name")[0].childNodes[0].nodeValue
});
(function (marker, data) {
google.maps.event.addListener(marker, 'click', function (e) {
infoWindow.setContent(data);
infoWindow.open(map, marker);
});
})(marker, data);
}
}
</script>
I have loaded latitude and longitude from xml file for each store locations.
check this script,
<script type="text/javascript">
var locations = [
['Bondi Beach', 16.7997751, 96.15659660000906, 4],
['Coogee Beach', 16.7897762, 96.15659660008007, 5],
['Cronulla Beach', 16.775815, 96.13637070000004, 3],
['Manly Beach', 16.7996784, 96.15659660000609, 2],
['Maroubra Beach', 16.7497795, 96.15659660050010, 1]
];
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 13,
center: new google.maps.LatLng(16.7997751, 96.15659660000006),
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][1], locations[i][2]),
map: map
});
google.maps.event.addListener(marker, 'click', (function (marker, i) {
return function () {
infowindow.setContent(locations[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
}
</script>
I have this code that reads data from an xml file and puts the marker on the map.
What i want to do is to read the xml file automatically every 5 seconds, and so update the position of the marker.
I tried adding setInterval to the function, but the problem is that the previous marker is not deleted. Just add another marker to the map and so on.
(I dont want the entire map updated, just the marker)
<script type="text/javascript">
var map = null;
function createMarker(latlng, html) {
var contentString = html;
var image = new google.maps.MarkerImage('http://www.google.com/mapfiles/markerA.png',
new google.maps.Size(20, 34),
new google.maps.Point(0,0),
new google.maps.Point(10, 34));
var shadow = new google.maps.MarkerImage('http://www.google.com/mapfiles/shadow50.png',
new google.maps.Size(37, 34),
new google.maps.Point(0,0),
new google.maps.Point(10, 34));
var marker = new google.maps.Marker({
position: latlng,
map: map,
shadow: shadow,
icon: image,
zIndex: Math.round(latlng.lat()*-100000)<<5
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(contentString);
infowindow.open(map,marker);
});
}
function initialize() {
var myOptions = {
zoom: 13,
center: new google.maps.LatLng(-18.432713,-70.317993),
mapTypeControl: true,
mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU},
navigationControl: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"),myOptions);
google.maps.event.addListener(map, 'click', function() {
infowindow.close();
});
setInterval(function() {
downloadUrl("data.xml", function(doc) {
var xmlDoc = xmlParse(doc);
var markers = xmlDoc.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var lat = parseFloat(markers[i].getAttribute("lat"));
var lng = parseFloat(markers[i].getAttribute("lng"));
var point = new google.maps.LatLng(lat,lng);
var html = "<strong>Taxi Arica</strong></br><strong>Latitud:</strong> " + markers[i].getAttribute("lat") + "</br><strong>Longitud:</strong> " + markers[i].getAttribute("lng");
var marker = createMarker(point,html);
}
});
},5000);
}
var infowindow = new google.maps.InfoWindow(
{size: new google.maps.Size(150,50)});
</script>
To update the position of a marker, you should call setPosition:
var new_marker_position = new google.maps.LatLng(53.345735, -6.259548);
marker.setPosition(new_marker_position);