I have had great result using the Javascript from Miguel Marnoto's Codepen for two instances of Google Maps, now I'm trying to expand to three or four instances, I attempted to initialize by naming the two other instaces, MapRIght and MapThree below. I'm not having any luck, can anyone advise on how to extend what Miguel wrote here in the original Javascript CodePen.
https://codepen.io/Marnoto/pen/VLjVZZ
My new version is below.
// *
// * Two maps on the same page, expanded to three
// * 2015 - en.marnoto.com
// *
// necessary variables
var mapLeft, mapRight, mapThree;
var infoWindowLeft, infoWindowRight, infoWindowThree;
// markersData variable stores the information necessary to each marker
var markersDataLeft = [
{
lat: 40.6486333,
lng: -8.745,
name: "Camping Praia do Farol",
address1:"Rua Diogo Cão, 125",
address2: "Praia da Barra",
postalCode: "3830-772 Gafanha da Nazaré" // don't insert comma in the last item of each marker
},
{
lat: 40.54955,
lng: -8.7498167,
name: "Camping Costa Velha",
address1:"Quinta dos Patos, n.º 2",
address2: "Praia da Costa Nova",
postalCode: "3830-453 Gafanha da Encarnação" // don't insert comma in the last item of each marker
},
{
lat: 40.6447167,
lng: -8.7129167,
name: "Camping Gafanha da Boavista",
address1:"Rua dos Balneários do Complexo Desportivo",
address2: "Gafanha da Nazaré",
postalCode: "3830-225 Gafanha da Nazaré" // don't insert comma in the last item of each marker
} // don't insert comma in the last item
];
var markersDataRight = [
{
lat: 40.6386333,
lng: -8.745,
name: "Camping Praia da Barra",
address1:"Rua Diogo Cão, 125",
address2: "Praia da Barra",
postalCode: "3830-772 Gafanha da Nazaré" // don't insert comma in the last item of each marker
},
{
lat: 40.59955,
lng: -8.7498167,
name: "Camping Costa Nova",
address1:"Quinta dos Patos, n.º 2",
address2: "Praia da Costa Nova",
postalCode: "3830-453 Gafanha da Encarnação" // don't insert comma in the last item of each marker
},
{
lat: 40.6247167,
lng: -8.7129167,
name: "Camping Gafanha da Nazaré",
address1:"Rua dos Balneários do Complexo Desportivo",
address2: "Gafanha da Nazaré",
postalCode: "3830-225 Gafanha da Nazaré" // don't insert comma in the last item of each marker
} // don't insert comma in the last item
];
var markersDataThree = [
{
lat: 40.6386333,
lng: -8.745,
name: "Camping Praia da Barra",
address1:"Rua Diogo Cão, 125",
address2: "Praia da Barra",
postalCode: "3830-772 Gafanha da Nazaré" // don't insert comma in the last item of each marker
},
{
lat: 40.59955,
lng: -8.7498167,
name: "Camping Costa Nova",
address1:"Quinta dos Patos, n.º 2",
address2: "Praia da Costa Nova",
postalCode: "3830-453 Gafanha da Encarnação" // don't insert comma in the last item of each marker
},
{
lat: 40.6247167,
lng: -8.7129167,
name: "Camping Gafanha da Nazaré",
address1:"Rua dos Balneários do Complexo Desportivo",
address2: "Gafanha da Nazaré",
postalCode: "3830-225 Gafanha da Nazaré" // don't insert comma in the last item of each marker
} // don't insert comma in the last item
];
function initialize(setMap) {
var mapOptions;
if(setMap == "mapLeft") {
mapOptions = {
center: new google.maps.LatLng(40.601203,-8.668173),
zoom: 11,
mapTypeId: 'roadmap',
};
mapLeft = new google.maps.Map(document.getElementById('map-canvas- left'), mapOptions);
// a new Info Window is created
infoWindowLeft = new google.maps.InfoWindow();
// Event that closes the Info Window with a click on the map
google.maps.event.addListener(mapLeft, 'click', function() {
infoWindowLeft.close();
});
} else {
mapOptions = {
center: new google.maps.LatLng(40.601203,-8.668173),
zoom: 9,
mapTypeId: 'roadmap',
};
mapRight = new google.maps.Map(document.getElementById('map-canvas- right'), mapOptions);
// a new Info Window is created
infoWindowRight = new google.maps.InfoWindow();
// Event that closes the Info Window with a click on the map
google.maps.event.addListener(mapRight, 'click', function() {
infoWindowRight.close();
});
} else {
mapOptions = {
center: new google.maps.LatLng(40.601203,-8.668173),
zoom: 7,
mapTypeId: 'roadmap',
};
mapThree = new google.maps.Map(document.getElementById('map-canvas- three'), mapOptions);
// a new Info Window is created
infoWindowThree = new google.maps.InfoWindow();
// Event that closes the Info Window with a click on the map
google.maps.event.addListener(mapThree, 'click', function() {
infoWindowThree.close();
});
}
// Finally displayMarkers() function is called to begin the markers creation
displayMarkers(setMap);
// Create second map only when initialize function is called for the first time.
// Second time setMap is equal to mapRight, so this condition returns false and it will not run
if(setMap == "mapLeft"){
initialize("mapRight", "mapThree");
}
}
google.maps.event.addDomListener(window, 'load', function(){ initialize("mapLeft") });
// This function will iterate over markersData array
// creating markers with createMarker function
function displayMarkers(setMap){
var markersData;
var map;
if(setMap == "mapLeft"){
markersData = markersDataLeft;
map = mapLeft;
} else {
markersData = markersDataRight;
map = mapRight;
} else {
markersData = markersDataThree;
map = mapThree;
}
// this variable sets the map bounds according to markers position
var bounds = new google.maps.LatLngBounds();
// for loop traverses markersData array calling createMarker function for each marker
for (var i = 0; i < markersData.length; i++){
var latlng = new google.maps.LatLng(markersData[i].lat, markersData[i].lng);
var name = markersData[i].name;
var address1 = markersData[i].address1;
var address2 = markersData[i].address2;
var postalCode = markersData[i].postalCode;
createMarker(setMap, latlng, name, address1, address2, postalCode);
// marker position is added to bounds variable
bounds.extend(latlng);
}
// Finally the bounds variable is used to set the map bounds
// with fitBounds() function
map.fitBounds(bounds);
}
// This function creates each marker and it sets their Info Window content
function createMarker(setMap, latlng, name, address1, address2, postalCode){
var map;
var infoWindow;
if(setMap == "mapLeft"){
map = mapLeft;
infoWindow = infoWindowLeft;
} else {
map = mapRight;
infoWindow = infoWindowRight;
} else {
map = mapThree;
infoWindow = infoWindowThree;
}
var marker = new google.maps.Marker({
map: map,
position: latlng,
title: name
});
// This event expects a click on a marker
// When this event is fired the Info Window content is created
// and the Info Window is opened.
google.maps.event.addListener(marker, 'click', function() {
// Creating the content to be inserted in the infowindow
var iwContent = '<div id="iw_container">' +
'<div class="iw_title">' + name + '</div>' +
'<div class="iw_content">' + address1 + '<br />' +
address2 + '<br />' +
postalCode + '</div></div>';
// including content to the Info Window.
infoWindow.setContent(iwContent);
// opening the Info Window in the current map and at the current marker location.
infoWindow.open(map, marker);
});
}
Your code has syntax errors
1. there can only be one else in an if ... else if ... else ... statement.
2. the string passed into document.getElementById() has to match the actual DOM element id, you have extra spaces in yours.
proof of concept fiddle
code snippet:
// *
// * Two maps on the same page, expanded to three
// * 2015 - en.marnoto.com
// *
// necessary variables
var mapLeft, mapRight, mapThree;
var infoWindowLeft, infoWindowRight, infoWindowThree;
// markersData variable stores the information necessary to each marker
var markersDataLeft = [{
lat: 40.6486333,
lng: -8.745,
name: "Camping Praia do Farol",
address1: "Rua Diogo Cão, 125",
address2: "Praia da Barra",
postalCode: "3830-772 Gafanha da Nazaré" // don't insert comma in the last item of each marker
}, {
lat: 40.54955,
lng: -8.7498167,
name: "Camping Costa Velha",
address1: "Quinta dos Patos, n.º 2",
address2: "Praia da Costa Nova",
postalCode: "3830-453 Gafanha da Encarnação" // don't insert comma in the last item of each marker
}, {
lat: 40.6447167,
lng: -8.7129167,
name: "Camping Gafanha da Boavista",
address1: "Rua dos Balneários do Complexo Desportivo",
address2: "Gafanha da Nazaré",
postalCode: "3830-225 Gafanha da Nazaré" // don't insert comma in the last item of each marker
} // don't insert comma in the last item
];
var markersDataRight = [{
lat: 40.6386333,
lng: -8.745,
name: "Camping Praia da Barra",
address1: "Rua Diogo Cão, 125",
address2: "Praia da Barra",
postalCode: "3830-772 Gafanha da Nazaré" // don't insert comma in the last item of each marker
}, {
lat: 40.59955,
lng: -8.7498167,
name: "Camping Costa Nova",
address1: "Quinta dos Patos, n.º 2",
address2: "Praia da Costa Nova",
postalCode: "3830-453 Gafanha da Encarnação" // don't insert comma in the last item of each marker
}, {
lat: 40.6247167,
lng: -8.7129167,
name: "Camping Gafanha da Nazaré",
address1: "Rua dos Balneários do Complexo Desportivo",
address2: "Gafanha da Nazaré",
postalCode: "3830-225 Gafanha da Nazaré" // don't insert comma in the last item of each marker
} // don't insert comma in the last item
];
var markersDataThree = [{
lat: 40.6386333,
lng: -8.745,
name: "Camping Praia da Barra",
address1: "Rua Diogo Cão, 125",
address2: "Praia da Barra",
postalCode: "3830-772 Gafanha da Nazaré" // don't insert comma in the last item of each marker
}, {
lat: 40.59955,
lng: -8.7498167,
name: "Camping Costa Nova",
address1: "Quinta dos Patos, n.º 2",
address2: "Praia da Costa Nova",
postalCode: "3830-453 Gafanha da Encarnação" // don't insert comma in the last item of each marker
}, {
lat: 40.6247167,
lng: -8.7129167,
name: "Camping Gafanha da Nazaré",
address1: "Rua dos Balneários do Complexo Desportivo",
address2: "Gafanha da Nazaré",
postalCode: "3830-225 Gafanha da Nazaré" // don't insert comma in the last item of each marker
} // don't insert comma in the last item
];
function initialize(setMap) {
var mapOptions;
if (setMap == "mapLeft") {
mapOptions = {
center: new google.maps.LatLng(40.601203, -8.668173),
zoom: 11,
mapTypeId: 'roadmap',
};
mapLeft = new google.maps.Map(document.getElementById('map-canvas-left'), mapOptions);
// a new Info Window is created
infoWindowLeft = new google.maps.InfoWindow();
// Event that closes the Info Window with a click on the map
google.maps.event.addListener(mapLeft, 'click', function() {
infoWindowLeft.close();
});
} else if (setMap == "mapRight") {
mapOptions = {
center: new google.maps.LatLng(40.601203, -8.668173),
zoom: 9,
mapTypeId: 'roadmap',
};
mapRight = new google.maps.Map(document.getElementById('map-canvas-right'), mapOptions);
// a new Info Window is created
infoWindowRight = new google.maps.InfoWindow();
// Event that closes the Info Window with a click on the map
google.maps.event.addListener(mapRight, 'click', function() {
infoWindowRight.close();
});
} else if (setMap == "mapThree") {
mapOptions = {
center: new google.maps.LatLng(40.601203, -8.668173),
zoom: 7,
mapTypeId: 'roadmap',
};
mapThree = new google.maps.Map(document.getElementById('map-canvas-three'), mapOptions);
// a new Info Window is created
infoWindowThree = new google.maps.InfoWindow();
// Event that closes the Info Window with a click on the map
google.maps.event.addListener(mapThree, 'click', function() {
infoWindowThree.close();
});
}
// Finally displayMarkers() function is called to begin the markers creation
displayMarkers(setMap);
// Create second map only when initialize function is called for the first time.
// Second time setMap is equal to mapRight, so this condition returns false and it will not run
if (setMap == "mapLeft") {
initialize("mapRight");
} else if (setMap == "mapRight") {
initialize("mapThree");
}
}
google.maps.event.addDomListener(window, 'load', function() {
initialize("mapLeft")
});
// This function will iterate over markersData array
// creating markers with createMarker function
function displayMarkers(setMap) {
var markersData;
var map;
if (setMap == "mapLeft") {
markersData = markersDataLeft;
map = mapLeft;
} else if (setMap == "mapRight") {
markersData = markersDataRight;
map = mapRight;
} else {
markersData = markersDataThree;
map = mapThree;
}
// this variable sets the map bounds according to markers position
var bounds = new google.maps.LatLngBounds();
// for loop traverses markersData array calling createMarker function for each marker
for (var i = 0; i < markersData.length; i++) {
var latlng = new google.maps.LatLng(markersData[i].lat, markersData[i].lng);
var name = markersData[i].name;
var address1 = markersData[i].address1;
var address2 = markersData[i].address2;
var postalCode = markersData[i].postalCode;
createMarker(setMap, latlng, name, address1, address2, postalCode);
// marker position is added to bounds variable
bounds.extend(latlng);
}
// Finally the bounds variable is used to set the map bounds
// with fitBounds() function
map.fitBounds(bounds);
}
// This function creates each marker and it sets their Info Window content
function createMarker(setMap, latlng, name, address1, address2, postalCode) {
var map;
var infoWindow;
if (setMap == "mapLeft") {
map = mapLeft;
infoWindow = infoWindowLeft;
} else if (setMap == "mapRight") {
map = mapRight;
infoWindow = infoWindowRight;
} else {
map = mapThree;
infoWindow = infoWindowThree;
}
var marker = new google.maps.Marker({
map: map,
position: latlng,
title: name
});
// This event expects a click on a marker
// When this event is fired the Info Window content is created
// and the Info Window is opened.
google.maps.event.addListener(marker, 'click', function() {
// Creating the content to be inserted in the infowindow
var iwContent = '<div id="iw_container">' +
'<div class="iw_title">' + name + '</div>' +
'<div class="iw_content">' + address1 + '<br />' +
address2 + '<br />' +
postalCode + '</div></div>';
// including content to the Info Window.
infoWindow.setContent(iwContent);
// opening the Info Window in the current map and at the current marker location.
infoWindow.open(map, marker);
});
}
html {
height: 100%;
}
body {
height: 100%;
margin: 0;
padding: 0;
}
.container {
width: 100%;
display: flex;
}
#map-canvas-left,
#map-canvas-right,
#map-canvas-three {
height: 250px;
width: 550px;
}
#iw_container .iw_title {
font-size: 16px;
font-weight: bold;
}
.iw_content {
padding: 15px 15px 15px 0;
}
<script src="https://maps.googleapis.com/maps/api/js?libraries=geometry,places&ext=.js"></script>
<div class="container">
<div id="map-canvas-left"></div>
<div id="map-canvas-right"></div>
<div id="map-canvas-three"></div>
</div>
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
Looking to clear all marker clusters using on click from a floating panel. I can clear and show all markers but not the marker clustered icons. I have scoured through multiple similar questions but am missing something for sure.
When I try to use the below code it comes back with markerCluster is not defined at clearMarkers.
JS Code:
var map;
var geocoder;
var markerAll;
var markers = [];
//Code to load the map with center point of Monterey MA
function initMap() {
var monterey = {lat: 42.181613, lng: -73.215013};
map = new google.maps.Map(document.getElementById('map'), {
zoom: 10,
center: monterey,
mapTypeId: google.maps.MapTypeId.HYBRID,
labels: true,
});
//collect customer data and geocoder object - declare geocoder as global
var cusdata = JSON.parse(document.getElementById('data').innerHTML);
geocoder = new google.maps.Geocoder();
codeAddress(cusdata);
var allData = JSON.parse(document.getElementById('allData').innerHTML);
showAllCustomers(allData);
var searchData = JSON.parse(document.getElementById('searchData').innerHTML);
showSearchedCustomer(searchData);
}
function showAllCustomers(allData) {
//declare info window variable outside of loop to allow to clear when selecting other markers
var infoWind = new google.maps.InfoWindow;
//Create marker clusterer to group data
var markerCluster = new MarkerClusterer(map, [], {
imagePath: 'images/m'
});
Array.prototype.forEach.call(allData, function(data){
var content = document.createElement('div');
var strong = document.createElement('strong');
strong.textContent = [data.lastName + ' ' + data.physicalAddress];
content.appendChild(strong);
//add image to infowindow - you are also able to add image path to mysql and then append dynamically
// var img = document.createElement('img');
// img.src = 'images/santahat.png';
// img.style.width = '50px';
// content.appendChild(img);
//Create markers for customer locations and customize
var iconBase = 'https://maps.google.com/mapfiles/kml/shapes/';
var markerAll = new google.maps.Marker({
position: new google.maps.LatLng(data.latitude, data.longitude),
map: map,
icon: iconBase + 'homegardenbusiness.png'
});
//push markers to marker clusterer
markerCluster.addMarker(markerAll);
markers.push(markerAll);
})
}
// Sets the map on all markers in the array.
function setMapOnAll(map) {
for (let i = 0; i < markers.length; i++) {
markers[i].setMap(map);
}
}
// Removes the markers from the map, but keeps them in the array.
function clearMarkers() {
setMapOnAll(null);
markerCluster.clearMarkers(markerAll); <----- THIS IS WHAT I TRIED TO ADD TO CLEAR CLUSTERS
}
// Shows any markers currently in the array.
function showMarkers() {
setMapOnAll(map);
}
You need to put the markerCluster in the global scope so it can be used in the clearMarkers function (which is (probably) defined in the the global scope).
var markerCluster;
function showAllCustomers(allData) {
//Create marker clusterer to group data
markerCluster = new MarkerClusterer(map, [], {
imagePath:
"https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m",
});
proof of concept fiddle
code snippet:
var map;
var geocoder;
var markerAll;
var markers = [];
//Code to load the map with center point of Monterey MA
function initMap() {
var monterey = {
lat: 42.181613,
lng: -73.215013
};
map = new google.maps.Map(document.getElementById('map'), {
zoom: 3,
center: {
lat: -28.024,
lng: 140.887
},
mapTypeId: google.maps.MapTypeId.HYBRID,
labels: true,
});
//collect customer data and geocoder object - declare geocoder as global
var cusdata = JSON.parse(document.getElementById('data').innerHTML);
geocoder = new google.maps.Geocoder();
// codeAddress(cusdata);
var allData = JSON.parse(document.getElementById('allData').innerHTML);
allData = locations;
showAllCustomers(allData);
var searchData = JSON.parse(document.getElementById('searchData').innerHTML);
// searchData = locations;
// showSearchedCustomer(searchData);
}
var markerCluster;
function showAllCustomers(allData) {
//Create marker clusterer to group data
markerCluster = new MarkerClusterer(map, [], {
imagePath: 'https://unpkg.com/#google/markerclustererplus#4.0.1/images/m',
});
//declare info window variable outside of loop to allow to clear when selecting other markers
var infoWind = new google.maps.InfoWindow;
Array.prototype.forEach.call(allData, function(data) {
var content = document.createElement('div');
var strong = document.createElement('strong');
strong.textContent = [data.lastName + ' ' + data.physicalAddress];
content.appendChild(strong);
//add image to infowindow - you are also able to add image path to mysql and then append dynamically
// var img = document.createElement('img');
// img.src = 'images/santahat.png';
// img.style.width = '50px';
// content.appendChild(img);
//Create markers for customer locations and customize
var iconBase = 'https://maps.google.com/mapfiles/kml/shapes/';
var markerAll = new google.maps.Marker({
position: new google.maps.LatLng(data.latitude, data.longitude),
map: map,
// icon: iconBase + 'homegardenbusiness.png'
});
//push markers to marker clusterer
markerCluster.addMarker(markerAll);
markers.push(markerAll);
})
google.maps.event.addDomListener(document.getElementById('btn'), 'click', clearMarkers);
}
// Sets the map on all markers in the array.
function setMapOnAll(map) {
for (let i = 0; i < markers.length; i++) {
markers[i].setMap(map);
}
}
// Removes the markers from the map, but keeps them in the array.
function clearMarkers() {
setMapOnAll(null);
markerCluster.clearMarkers(markerAll);
}
// Shows any markers currently in the array.
function showMarkers() {
setMapOnAll(map);
}
const locations = [{
latitude: -31.56391,
longitude: 147.154312,
lastName: "Smith",
physicalAddress: "New York, NY"
},
{
latitude: -33.718234,
longitude: 150.363181,
lastName: "Smith",
physicalAddress: "New York, NY"
},
{
latitude: -33.727111,
longitude: 150.371124,
lastName: "Smith",
physicalAddress: "New York, NY"
},
{
latitude: -33.848588,
longitude: 151.209834,
lastName: "Smith",
physicalAddress: "New York, NY"
},
{
latitude: -33.851702,
longitude: 151.216968,
lastName: "Smith",
physicalAddress: "New York, NY"
},
{
latitude: -34.671264,
longitude: 150.863657,
lastName: "Smith",
physicalAddress: "New York, NY"
},
{
latitude: -35.304724,
longitude: 148.662905,
lastName: "Smith",
physicalAddress: "New York, NY"
},
{
latitude: -36.817685,
longitude: 175.699196,
lastName: "Smith",
physicalAddress: "New York, NY"
},
{
latitude: -36.828611,
longitude: 175.790222,
lastName: "Smith",
physicalAddress: "New York, NY"
},
{
latitude: -37.75,
longitude: 145.116667,
lastName: "Smith",
physicalAddress: "New York, NY"
},
{
latitude: -37.759859,
longitude: 145.128708,
lastName: "Smith",
physicalAddress: "New York, NY"
},
{
latitude: -37.765015,
longitude: 145.133858,
lastName: "Smith",
physicalAddress: "New York, NY"
},
{
latitude: -37.770104,
longitude: 145.143299,
lastName: "Smith",
physicalAddress: "New York, NY"
},
{
latitude: -37.7737,
longitude: 145.145187,
lastName: "Smith",
physicalAddress: "New York, NY"
},
{
latitude: -37.774785,
longitude: 145.137978,
lastName: "Smith",
physicalAddress: "New York, NY"
},
{
latitude: -37.819616,
longitude: 144.968119,
lastName: "Smith",
physicalAddress: "New York, NY"
},
{
latitude: -38.330766,
longitude: 144.695692,
lastName: "Smith",
physicalAddress: "New York, NY"
},
{
latitude: -39.927193,
longitude: 175.053218,
lastName: "Smith",
physicalAddress: "New York, NY"
},
{
latitude: -41.330162,
longitude: 174.865694,
lastName: "Smith",
physicalAddress: "New York, NY"
},
{
latitude: -42.734358,
longitude: 147.439506,
lastName: "Smith",
physicalAddress: "New York, NY"
},
{
latitude: -42.734358,
longitude: 147.501315,
lastName: "Smith",
physicalAddress: "New York, NY"
},
{
latitude: -42.735258,
longitude: 147.438,
lastName: "Smith",
physicalAddress: "New York, NY"
},
{
latitude: -43.999792,
longitude: 170.463352,
lastName: "Smith",
physicalAddress: "New York, NY"
},
];
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
<!DOCTYPE html>
<html>
<head>
<title>Marker Clustering</title>
<script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
<script src="https://unpkg.com/#google/markerclustererplus#4.0.1/dist/markerclustererplus.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap&libraries=&v=weekly" defer></script>
<!-- jsFiddle will insert css and js -->
</head>
<body>
<input id="btn" type="button" value="Clear Markers" />
<div id="map"></div>
<div id="data">[]</div>
<div id="allData">[]</div>
<div id="searchData">[]</div>
</body>
</html>
I'm going to initalize infowindows (for google map markers) through angular controller (i'm using ng-map module)
NgMap.getMap().then (map) ->
$scope.map = map
for marker in markers
latLng = new (google.maps.LatLng)(marker.latitude, marker.longitude)
#initialize infoWindows through google map api, not ng-map module
contentString = 'is an example string'
infoWindow = new (google.maps.InfoWindow)(content: contentString)
$scope.dynMarkers.push new (google.maps.Marker)(position: latLng)
marker.addListener 'click', ->
infoWindow.open map, marker
$scope.markerClusterer = new MarkerClusterer(map,$scope.dynMarkers, {})
I have an error in console:
marker.addListener is not a function
I can't use an ng-map 'infowindow' DOM element in my view.
What's wrong?
marker object needs to be of google.maps.Marker type, try to replace:
$scope.dynMarkers.push new (google.maps.Marker)(position: latLng)
marker.addListener 'click', ->
infoWindow.open map, marker
with
markerObject = new (google.maps.Marker)(position: latLng) #<-Marker object
$scope.dynMarkers.push markerObject
markerObject.addListener 'click', ->
infoWindow.open map, markerObject
Example
angular.module('mapApp', ['ngMap'])
.controller('mapController', function ($scope, NgMap) {
NgMap.getMap().then(function (map) {
$scope.map = map;
$scope.dynMarkers = [];
$scope.markers.forEach(function (marker) {
var latLng = new google.maps.LatLng(marker.latitude, marker.longitude);
var contentString = 'is an example string'
var infoWindow = new (google.maps.InfoWindow)({ content: contentString });
var dynMarker = new google.maps.Marker({ position: latLng });
$scope.dynMarkers.push(dynMarker);
google.maps.event.addListener(dynMarker, 'click', function () {
infoWindow.open(map,dynMarker);
});
});
var mcOptions = { imagePath: 'https://cdn.rawgit.com/googlemaps/js-marker-clusterer/gh-pages/images/m' };
$scope.markerClusterer = new MarkerClusterer(map, $scope.dynMarkers, mcOptions)
});
$scope.markers = [
{ id: 1, name: 'Oslo', latitude: 59.923043, longitude: 10.752839 },
{ id: 2, name: 'Stockholm', latitude: 59.339025, longitude: 18.065818 },
{ id: 3, name: 'Copenhagen', latitude: 55.675507, longitude: 12.574227 },
{ id: 4, name: 'Berlin', latitude: 52.521248, longitude: 13.399038 },
{ id: 5, name: 'Paris', latitude: 48.856127, longitude: 2.346525 }
];
});
<script src="https://code.angularjs.org/1.4.8/angular.js"></script>
<script src="https://maps.googleapis.com/maps/api/js"></script>
<script src="https://rawgit.com/allenhwkim/angularjs-google-maps/master/build/scripts/ng-map.js"></script>
<script src="https://googlemaps.github.io/js-marker-clusterer/src/markerclusterer.js"></script>
<div ng-app="mapApp" ng-controller="mapController">
<ng-map default-style="true" zoom="3" center="59.339025, 18.065818">
</ng-map>
</div>
Let's say I have a bunch of markers (over 100) I want to add from this:
module.exports = [
{ value: 'Varrock', lng: 22.5, lat: -15.52249812756166, popular: 1 },
{ value: 'Lumbridge', lng: 25.9661865234375, lat: -43.644025847699496, popular: 1 },
{ value: 'Monastery', lng: -4.0924072265625, lat: -5.714379819235291 },
{ value: 'Edgeville', lng: 2.4884033203125, lat: -6.0094592380595495, popular: 1 },
{ value: 'Varrock Palace', lng: 22.412109375, lat: -6.882800241767556 },
{ value: 'Digsite', lng: 46.043701171875, lat: -17.266727823520508 },
{ value: 'River Salve', lng: 54.931640625, lat: -14.083301314706778 },
{ value: 'Morytania', lng: 64.610595703125, lat: -13.501814172428656 },
{ value: 'Mort Myre Swamp', lng: 59.820556640625, lat: -22.740723091194727 }
];
It uses browserify to get it. So, I do this:
var locations = require('./locations');
What would be the best way to add all of those into LayerGroup()? I mean, because doing var fairy = L.layerGroup([One, Two, Three...]); by hand would get tiresome.
So how would I go about adding all of those markers into a new layer (so I can toggle them on/off)
How about adding an empty L.LayerGroup, looping over your array and adding them to that layer?
var locations = [];
var layer = L.layerGroup().addTo(map);
locations.forEach(function (location) {
L.marker([location.lat, location.lng])
.bindPopup(location.value)
.addTo(layer);
});
Working example on Plunker: http://plnkr.co/edit/Q0DGqs?p=preview
I have a jQuery plugin that loads content into a certain div. Ignore the drawmap function at the beginning. It only serves in one of the pages. I'm trying to load content into the div while updating the url (not redirecting). For example, if I click on About Us the url will show: calstateautoparts.com/beta/aboutus.html. If I click on contact us the url will show calstateautoparts.com/beta/contactus.html.
Also, I would like to have the plugin load a page in the div by default, home.html. How do I make both of these changes in my code?
You can see the live site at: http://calstateautoparts.com/beta
<script type="text/javascript">
jQuery(function($){
function drawmap(){
new Maplace({
locations: [
{
lat: 33.8583,
lon: -117.8678,
title: 'Anaheim',
html: [
'<h3>Anaheim</h3>',
'<p>1361 N RedGum St, Anaheim CA 92806<br>(714) 630-5954</p>'
].join(''),
zoom: 8
},
{
lat: 34.2358,
lon: -118.5739,
title: 'Chatsworth',
html: [
'<h3>Chatsworth</h3>',
'<p>20233 Corisco St, Chatsworth CA 91311<br>(818) 998-3001</p>'
].join(''),
zoom: 8
},
{
lat: 32.8142,
lon: -117.1247,
title: 'San Diego',
html: [
'<h3>San Diego</h3>',
'<p>4000 Ruffin Road Suite K, San Diego CA 92123<br>(858) 292-1622</p>'
].join(''),
zoom: 8
}
,
{
lat: 34.9137,
lon: -120.4632,
title: 'Santa Maria',
html: [
'<h3>Santa Maria</h3>',
'<p>1459 W. Fairway Dr., Santa Maria CA 93455<br>(805) 922-4445</p>'
].join(''),
zoom: 8
}
,
{
lat: 34.5011,
lon: -117.3279,
title: 'Victorville',
html: [
'<h3>Victorville</h3>',
'<p>15400-B Tamarack Road, Victorville CA 92392<br>(760) 243-5666</p>'
].join(''),
zoom: 8
}
,
{
lat: 36.1605,
lon: -115.1050,
title: 'Las Vegas',
html: [
'<h3>Las Vegas</h3>',
'<p>3101 Builders Ave., Las Vegas, NV 89101<br>(702) 452-2440</p>'
].join(''),
zoom: 8
}
,
{
lat: 33.1677,
lon: -117.2202,
title: 'Vista',
html: [
'<h3>Vista</h3>',
'<p>2055 Thibodo Rd, Vista CA 92081<br>(760) 599-0791</p>'
].join(''),
zoom: 8
}
,
{
lat: 33.6224,
lon: -117.7194,
title: 'Laguna Hills',
html: [
'<h3>Laguna Hills</h3>',
'<p>23561 Ridge Route Suite P, Laguna Hills CA 92653<br>(949) 699-3308</p>'
].join(''),
zoom: 8
}
,
{
lat: 34.4245,
lon: -118.4998,
title: 'Santa Clarita',
html: [
'<h3>Santa Clarita</h3>',
'<p>26846 Oak Ave Unit R, Santa Clarita CA 91315<br>(661) 424-9396</p>'
].join(''),
zoom: 8
}
],
map_div: '#gmap-list',
controls_type: 'list',
controls_title: 'Choose a location:'
}).Load();
}
$('.menuitem').click(function(e){
$('#contentarea').load(this.href, $(this).data('loadfunc') || null);
e.preventDefault();
});
$('#contactus').data({loadfunc: drawmap});
});
</script>
Currently, I am displaying 500-600 Markers on Google map, with their names as tooltip. Now,
I need to display the tool-tip of all overlapping markers as comma-separated i.e. Marker1, Marker2, Marker3 etc. if Marker1, Marker2, Marker3 are overlapped on map.
I found many other different examples on google map at internet especially at GeoCodeZip, but not of my requirement.
if this requirement is once filled, Am afraid of performance issues on zoom changed events, as tooltip needed to be updated (if overlapping is changed).
Update1 : I have already show Overlapping Marker spiderfier to client but not acceptable.
Does anyone have right path or working example ?
Thanks
-Anil
The core of this is to find the pixel distance between LatLngs. Then before adding each marker check the pixel distance between it and any existing markers. If there is another marker nearby add to the title otherwise create a new marker. jsFiddle
function init() {
var mapOptions = {
center: new google.maps.LatLng(0, -0),
zoom: 4,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map-canvas'),mapOptions);
// to get the pixel position from the latlng
// https://stackoverflow.com/questions/1538681/how-to-call-fromlatlngtodivpixel-in-google-maps-api-v3
var overlay = new google.maps.OverlayView();
overlay.draw = function() {};
overlay.setMap(map);
google.maps.event.addListenerOnce(map, 'idle', function() {
if (overlay.getProjection()) {
var points = [
{ latlng: new google.maps.LatLng(40, -100), title: '1' },
{ latlng: new google.maps.LatLng(40.125, -100.125), title: '2' },
{ latlng: new google.maps.LatLng(40.25, -100.25), title: '3' },
{ latlng: new google.maps.LatLng(40.5, -100.5), title: '4' },
{ latlng: new google.maps.LatLng(40.75, -100.75), title: '5' },
{ latlng: new google.maps.LatLng(41, -101), title: '6' },
{ latlng: new google.maps.LatLng(35, -95), title: '7' },
{ latlng: new google.maps.LatLng(45, 105), title: '8' },
{ latlng: new google.maps.LatLng(25, -115), title: '9' },
{ latlng: new google.maps.LatLng(55, -85), title: '10' },
{ latlng: new google.maps.LatLng(30, -34), title: '11' }
];
// for each point
var markers = [];
points.forEach(function (point) {
var nearby = false;
var pointPixelPosition = overlay.getProjection().fromLatLngToContainerPixel(point.latlng);
markers.forEach(function(marker) {
var markerPixelPosition = overlay.getProjection().fromLatLngToContainerPixel(marker.getPosition());
// check for marker 'near by'
if (Math.abs(pointPixelPosition.x - markerPixelPosition.x) < 10 || Math.abs(pointPixelPosition.y - markerPixelPosition.y) < 10) {
nearby = true;
marker.setTitle(marker.getTitle() + ', ' + point.title);
}
});
// create new marker
if (!nearby) {
markers.push(new google.maps.Marker({ map: map, position: point.latlng, title: point.title }));
}
});
}
map.setCenter(new google.maps.LatLng(39.8282, -98.5795));
});
}