Marker Clustering on Google Maps with JSON multi markers - javascript

I've created a map with multi markers from a JSON file. I'm trying to add a marker cluster, but I'm ending up with the cluster and markers showing at the same time.
This is what I see at the moment:
I've added the script below to my index.html page:
<script src="https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/markerclusterer.js"></script>
This is the relevant part of my maps.js file:
let map;
let jsonData = "assets/Data/maps.json";
const countries = [
{ lat: 48.857497, lng: 2.347628, zoom: 5, name: "France" },
//Brazil
{ lat: -15.793889, lng: -47.882778, zoom: 5, name: "Brazil" }
];
function initMap() {
const mapOptions = {
center: {
lat: 9.072264,
lng: 7.491302
},
zoom: 2,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map"), mapOptions);
countries.forEach(function (data) {
let countriesMarker = new google.maps.Marker({
map: map,
position: { lat: data.lat, lng: data.lng },
title: data.name
});
$("#selectlocation").append('<option value="' + [data.lat, data.lng, data.zoom].join('|') + '">' + data.name + '</option>');
});
let infowindow = new google.maps.InfoWindow();
//Method found on StackOverflow: https://stackoverflow.com/questions/28606149/load-data-from-json-file-into-map-markers-in-google-maps
$.getJSON(jsonData, function (jsonMarkers) {
$.each(jsonMarkers.markers, function (key, data) {
let latLng = new google.maps.LatLng(data.lat, data.lng);
let marker = new google.maps.Marker({
position: latLng,
map: map,
title: data.title
});
var clusterMarkers = jsonMarkers.markers.map(function (location) {
return new google.maps.Marker({
position: location
});
});
var markerCluster = new MarkerClusterer(map, clusterMarkers,
{ imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m' });
});
});
}

You have multiple issues.
As #xomena indicated you are creating the markers twice, remove one of those sets of code.
You are creating a MarkerClusterer for each marker. Move the creation of the MarkerClusterer out of the loop that creates the markers.
Something like this should work:
$.each(jsonMarkers.markers, function (key, data) {
let latLng = new google.maps.LatLng(data.lat, data.lng);
let marker = new google.maps.Marker({
position: latLng,
map: map,
title: data.title
});
clusterMarkers.push(marker);
});
var markerCluster = new MarkerClusterer(map, clusterMarkers,
{ imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m'
});
proof of concept fiddle
code snippet:
let map;
let jsonData = "assets/Data/maps.json";
const countries = [
{ lat: 48.857497, lng: 2.347628, zoom: 5, name: "France" },
//Brazil
{ lat: -15.793889, lng: -47.882778, zoom: 5, name: "Brazil" }
];
function initMap() {
const mapOptions = {
center: {
lat: -19.072264,
lng: 117.491302
},
zoom: 1,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map"), mapOptions);
countries.forEach(function (data) {
let countriesMarker = new google.maps.Marker({
map: map,
position: { lat: data.lat, lng: data.lng },
title: data.name
});
$("#selectlocation").append('<option value="' + [data.lat, data.lng, data.zoom].join('|') + '">' + data.name + '</option>');
});
let infowindow = new google.maps.InfoWindow();
let clusterMarkers = [];
//Method found on StackOverflow: https://stackoverflow.com/questions/28606149/load-data-from-json-file-into-map-markers-in-google-maps
// $.getJSON(jsonData, function (jsonMarkers) {
var jsonMarkers = {markers: [
{lat: -31.563910, lng: 147.154312},
{lat: -33.718234, lng: 150.363181},
{lat: -33.727111, lng: 150.371124},
{lat: -33.848588, lng: 151.209834},
{lat: -33.851702, lng: 151.216968},
{lat: -34.671264, lng: 150.863657},
{lat: -35.304724, lng: 148.662905},
{lat: -36.817685, lng: 175.699196},
{lat: -36.828611, lng: 175.790222},
{lat: -37.750000, lng: 145.116667},
{lat: -37.759859, lng: 145.128708},
{lat: -37.765015, lng: 145.133858},
{lat: -37.770104, lng: 145.143299},
{lat: -37.773700, lng: 145.145187},
{lat: -37.774785, lng: 145.137978},
{lat: -37.819616, lng: 144.968119},
{lat: -38.330766, lng: 144.695692},
{lat: -39.927193, lng: 175.053218},
{lat: -41.330162, lng: 174.865694},
{lat: -42.734358, lng: 147.439506},
{lat: -42.734358, lng: 147.501315},
{lat: -42.735258, lng: 147.438000},
{lat: -43.999792, lng: 170.463352}
]};
$.each(jsonMarkers.markers, function (key, data) {
let latLng = new google.maps.LatLng(data.lat, data.lng);
if (!data.title)
data.title = ""+key;
let marker = new google.maps.Marker({
position: latLng,
map: map,
title: data.title
});
clusterMarkers.push(marker);
});
var markerCluster = new MarkerClusterer(map, clusterMarkers,
{ imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m'
});
// });
}
/* 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;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="map"></div>
<script src="https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/markerclusterer.js"></script>
<!-- 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>

Related

Display error UTF-8 character in label of Google Maps markers

I have file foo.ftl
<script>
function initMap() {
const map = new google.maps.Map(document.getElementById("map"), {
zoom: 16,
center: {lat: 20.993514917846174, lng: 105.78660475957122},
});
// const labels = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
const labels = [
"The Light Trung Văn",
"Khu đô thị Mulbery Lane",
"Nhà thờ giáo xứ Phùng Khoang",
"Khỏe đẹp 24h"];
const locations = [
{ lat: 20.9935851166474, lng: 105.78857910579417 },
{ lat: 20.986910834987295, lng: 105.78535398147808 },
{ lat: 20.990339683019226, lng: 105.7922698253056 },
{ lat: 20.996770381033244, lng: 105.79321396285934 }
];
const markers = locations.map((location, i) => {
return new google.maps.Marker({
position: location,
label: labels[i % labels.length],
});
});
new MarkerClusterer(map, markers, {
imagePath:
"https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m",
});
const ecolife = {lat: 20.993514917846174, lng: 105.78660475957122};
// const map22 = new google.maps.Map(document.getElementById("map"), {
// zoom: 18,
// center: ecolife,
// });
// const marker = new google.maps.Marker({
// position: ecolife,
// map: map22,
// });
}
</script>
I see HTML source of web-page
Encoding in text editor
but still error font UTF-8
How to display text in UTF-8 correctly?
This is a defect of FreeMarker
<#ftl encoding="utf-8">
See https://freemarker.apache.org/docs/pgui_misc_charset.html#autoid_52

Getting marker info from markerclusterer

I have pushed markers into the a markerClusterer. When I click on the markerClusterer I want to display the info of the nmarkers in the cluster. However, when I use the getMarkers() method, it does not give me the info that I stored in marker, only data about the marker itself. Is there any way that I can implement this? https://codesandbox.io/s/joey-gmaps-c5kdf
const markerCluster = new MarkerClusterer(map, [],
{ imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m' });
google.maps.event.addListener(markerCluster, 'clusterclick', function (c) {
console.log('Number of managed markers in cluster: ' + c.getSize());
var m = c.getMarkers();
for (i in m) {
console.log(Object.values(m[i]));
console.log(m[i].getTitle());
console.log(m[i].toString());
}
var p = [];
for (var i = 0; i < m.length; i++) {
p.push(m[i]);
}
});
You can get your markers' information using getMarkers so there may be an issue somewhere in your code implementation that you haven't posted.
Try the following jsfiddle based off of Google's example.
JS code below:
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 3,
center: {
lat: -28.024,
lng: 140.887
}
});
var labels = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
var markers = locations.map(function(location, i) {
return new google.maps.Marker({
position: location,
label: labels[i % labels.length],
title: location.lat.toString() + "," + location.lng.toString(),
myObj: { myKey: i }
});
});
var markerCluster = new MarkerClusterer(map, markers, {
imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m'
});
google.maps.event.addListener(markerCluster, 'clusterclick', function(c) {
console.log('Number of managed markers in cluster: ' + c.getSize());
var m = c.getMarkers();
for (let i in m) {
console.log(m[i].getLabel());
console.log(m[i].getTitle());
console.log(m[i].myObj.myKey);
}
});
}
var locations = [{
lat: -31.563910,
lng: 147.154312
},
{
lat: -33.718234,
lng: 150.363181
},
{
lat: -33.727111,
lng: 150.371124
},
{
lat: -33.848588,
lng: 151.209834
},
{
lat: -33.851702,
lng: 151.216968
},
{
lat: -34.671264,
lng: 150.863657
},
{
lat: -35.304724,
lng: 148.662905
},
{
lat: -36.817685,
lng: 175.699196
},
{
lat: -36.828611,
lng: 175.790222
},
{
lat: -37.750000,
lng: 145.116667
},
{
lat: -37.759859,
lng: 145.128708
},
{
lat: -37.765015,
lng: 145.133858
},
{
lat: -37.770104,
lng: 145.143299
},
{
lat: -37.773700,
lng: 145.145187
},
{
lat: -37.774785,
lng: 145.137978
},
{
lat: -37.819616,
lng: 144.968119
},
{
lat: -38.330766,
lng: 144.695692
},
{
lat: -39.927193,
lng: 175.053218
},
{
lat: -41.330162,
lng: 174.865694
},
{
lat: -42.734358,
lng: 147.439506
},
{
lat: -42.734358,
lng: 147.501315
},
{
lat: -42.735258,
lng: 147.438000
},
{
lat: -43.999792,
lng: 170.463352
}
]
If e.g. you click on the blue cluster #3, you'll get the following output logged in the console:
Number of managed markers in cluster: 3
T
-42.734358,147.439506
U
-42.734358,147.501315
V
-42.735258,147.438
Edit: This error appears to be typescript related. There's a solution in related thread custom property with google marker in type script
Please try the code below:
for (var i = 0; i < features.length; i++) {
const marker2 = new google.maps.Marker({
position: features[i].position,
icon: icons[features[i].type].icon,
animation: google.maps.Animation.DROP,
map: map
});
marker2.set("customInfo", features[i].location);
console.log("Marker222223", marker2["customInfo"]);
markerCluster.addMarker(marker2);
}
Hope this helps!
While creating markers add object into marker so that each marker will have asociated object with it i.e. customInfo
var marker = new google.maps.Marker({
position: accident_LatLng,
title: accident_title,
map: map,
customInfo: object,
});
to Access marker object use below code. I have created custom array to store marker object.
var markers = cluster.getMarkers();
var markerCustom = [];
for (var i = 0; i < markers.length; i++) {
markerCustom.push(cluster.markers_[i].customInfo)
}
Hope this helps
Reference https://medium.com/#sunil.jadhav38/implementing-marker-clustering-is-angular-using-google-charts-6b62a33f3b61

Google Map Clustering not working with single location

I am using Google Map Clustering and opening Info Windows after clicking on particular cluster using clusterclick which is working absolutely fine.
However, when I have single location, its not going inside clusterclick event and hence I am unable to open my Info Window.
I am trying to add below events but its not firing when I have single location as data.
google.maps.event.addListener(markers, 'click', (function (markers) {
alert('markersclick');
})(markers));
google.maps.event.addListener(map, 'click', function () {
alert('mapclick');
});
Here is my full source code (I have not added Info Window code because as of not even above events not firing).
<div id="map"></div>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=MY_API_KEY">
</script>
<script src="https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/markerclusterer.js"></script>
<script>
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 3,
center: {lat: -28.024, lng: 140.887}
});
// Create an array of alphabetical characters used to label the markers.
var labels = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
var markers = locations.map(function(location, i) {
return new google.maps.Marker({
position: location,
label: labels[i % labels.length]
});
});
google.maps.event.addListener(markers, 'click', (function (markers) {
alert('markersclick');
})(markers));
google.maps.event.addListener(map, 'click', function () {
alert('mapclick');
});
// Add a marker clusterer to manage the markers.
var markerCluster = new MarkerClusterer(map, markers,
{imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m',
gridSize: 100,
zoomOnClick: true,
maxZoom: 10});
google.maps.clusterclick.addListener(markerCluster, "clusterclick", function(cluster, event) {
alert('hey');
});
}
var locations = [
{lat: -31.563910, lng: 147.154312},
{lat: -31.563910, lng: 147.154312},
{lat: -31.563910, lng: 147.154312},
{lat: -31.563910, lng: 147.154312},
{lat: -31.563910, lng: 147.154312},
{lat: -31.563910, lng: 147.154312},
{lat: -31.563910, lng: 147.154312},
{lat: -31.563910, lng: 147.154312},
{lat: -31.563910, lng: 147.154312},
{lat: -31.563910, lng: 147.154312},
{lat: -31.563910, lng: 147.154312},
{lat: -31.563910, lng: 147.154312},
{lat: -31.563910, lng: 147.154312},
{lat: -31.563910, lng: 147.154312},
{lat: -31.563910, lng: 147.154312},
{lat: -31.563910, lng: 147.154312},
{lat: -31.563910, lng: 147.154312},
{lat: -31.563910, lng: 147.154312},
{lat: -31.563910, lng: 147.154312},
{lat: -31.563910, lng: 147.154312},
{lat: -31.563910, lng: 147.154312},
{lat: -31.563910, lng: 147.154312},
{lat: -31.563910, lng: 147.154312},
{lat: -31.563910, lng: 147.154312}
];
initMap();
</script>
<style>
#map {
height: 100%;
}
</style>
If I change my locations array to something like this.
var locations = [
{lat: -31.563910, lng: 147.154312},
];
Then my clusterclick not firing as well as markers click event.
Also I am getting an error saying..
TypeError: google.maps.clusterclick is undefined
But I can have records like this.
Can someone guide me what I am doing wrong here ? Why its not working with single location ?
In the code you posted, markers is an array of google.maps.Marker objects. You can't add the listener on the array. You have to loop through your array and add the listener to each Marker individually.
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 3,
center: {
lat: -28.024,
lng: 140.887
}
});
// Create an array of alphabetical characters used to label the markers.
var labels = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
var locations = [{
lat: -31.563510,
lng: 147.154312
},
{
lat: -31.563610,
lng: 147.154312
},
{
lat: -31.563710,
lng: 147.154312
},
{
lat: -31.563810,
lng: 147.154312
}
];
var markers = [];
var infowindow = new google.maps.InfoWindow();
for (var i = 0; i < locations.length; i++) {
var marker = new google.maps.Marker({
position: locations[i],
map: map,
label: labels[i % labels.length]
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent('Label: ' + this.getLabel());
infowindow.open(map, this);
});
markers.push(marker);
}
// Add a marker clusterer to manage the markers.
var markerCluster = new MarkerClusterer(map, markers, {
imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m',
gridSize: 100,
zoomOnClick: true,
maxZoom: 10
});
}
initMap();
#map {
height: 200px;
}
<div id="map"></div>
<script src="https://maps.googleapis.com/maps/api/js"></script>
<script src="https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/markerclusterer.js"></script>

Autozoom and autocenter for Google maps Clustermap

What is the best way to add auto-zoom and auto-center a google cluster maps? Currently the center and zoom is hard-coded with conflicts with dynamically generated markers.
<<div id="map"></div>
<script>
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 3,
center: {lat: -28.024, lng: 140.887}
});
var labels = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
var markers = locations.map(function(location, i) {
return new google.maps.Marker({
position: location,
label: labels[i % labels.length]
});
});
// Add a marker clusterer to manage the markers.
var markerCluster = new MarkerClusterer(map, markers,
{imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m'});
}
var locations = [
{lat: -31.563910, lng: 147.154312},
{lat: -33.718234, lng: 150.363181},
{lat: -33.727111, lng: 150.371124},
{lat: -33.848588, lng: 151.209834},
{lat: -33.851702, lng: 151.216968},
{lat: -34.671264, lng: 150.863657},
{lat: -35.304724, lng: 148.662905},
{lat: -36.817685, lng: 175.699196},
{lat: -36.828611, lng: 175.790222},
{lat: -37.750000, lng: 145.116667},
{lat: -37.759859, lng: 145.128708},
{lat: -37.765015, lng: 145.133858},
{lat: -43.999792, lng: 170.463352}
]
</script>
<script src="https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/markerclusterer.js">
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
</script>
Add the marker locations to a google.maps.LatLngBounds object, then call map.fitBounds() on with the resulting bounds.
var bounds = new google.maps.LatLngBounds();
var markers = locations.map(function(location, i) {
bounds.extend(location);
map.fitBounds(bounds);
// ...
proof of concept fiddle
code snippet:
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 3,
center: {
lat: -28.024,
lng: 140.887
}
});
var labels = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
var bounds = new google.maps.LatLngBounds();
var markers = locations.map(function(location, i) {
bounds.extend(location);
map.fitBounds(bounds);
return new google.maps.Marker({
position: location,
label: labels[i % labels.length]
});
});
// Add a marker clusterer to manage the markers.
var markerCluster = new MarkerClusterer(map, markers, {
imagePath: 'https://cdn.jsdelivr.net/gh/googlemaps/v3-utility-library#07f15d84/markerclustererplus/images/m'
// was 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m'
});
}
var locations = [{
lat: -31.563910,
lng: 147.154312
}, {
lat: -33.718234,
lng: 150.363181
}, {
lat: -33.727111,
lng: 150.371124
}, {
lat: -33.848588,
lng: 151.209834
}, {
lat: -33.851702,
lng: 151.216968
}, {
lat: -34.671264,
lng: 150.863657
}, {
lat: -35.304724,
lng: 148.662905
}, {
lat: -36.817685,
lng: 175.699196
}, {
lat: -36.828611,
lng: 175.790222
}, {
lat: -37.750000,
lng: 145.116667
}, {
lat: -37.759859,
lng: 145.128708
}, {
lat: -37.765015,
lng: 145.133858
}, {
lat: -43.999792,
lng: 170.463352
}]
google.maps.event.addDomListener(window, "load", initMap);
html,
body,
#map {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<script src="https://cdn.jsdelivr.net/gh/googlemaps/v3-utility-library#07f15d84/markerclustererplus/src/markerclusterer.js"></script>
<!-- was https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/markerclusterer.js -->
<div id="map"></div>

Add Info window in Google Maps JavaScript API

I would like to ask about how to add an info window to a marker in Google Maps. The condition is, I have to create a program with multiple markers on a map. But how I can give a specified info window to each marker?
This is my code for now:
var markers = [];
var map;
var labels = 'ABCD';
var labelIndex = 0;
function initialize() {
map = new google.maps.Map(
document.getElementById("map"), {
center: new google.maps.LatLng(40.7127837, -74.0059413),
zoom: 11,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
// New York, NY, USA (40.7127837, -74.0059413)
// Newark, NJ, USA (40.735657, -74.1723667)
// Jersey City, NJ, USA (40.72815749999999, -74.07764170000002)
// Bayonne, NJ, USA (40.6687141, -74.11430910000001)
addMarker({
lat: 40.7127837,
lng: -74.0059413
}, "red");
addMarker({
lat: 40.735657,
lng: -74.1723667
}, "green");
addMarker({
lat: 40.7281575,
lng: -74.0776417
}, "yellow");
addMarker({
lat: 40.6687141,
lng: -74.1143091
}, "orange");
}
google.maps.event.addDomListener(window, "load", initialize);
function addMarker(location, color) {
var marker = new google.maps.Marker({
position: location,
label: labels[labelIndex++ % labels.length],
icon: {
url: 'http://maps.google.com/mapfiles/ms/icons/' + color + '.png',
labelOrigin: new google.maps.Point(15, 10)
},
map: map
});
markers.push(marker);
}
Can someone give me a solution on how to resolve my problem?
You could do it like this:
var markers = [];
var map;
var labels = 'ABCD';
var labelIndex = 0;
function initialize() {
map = new google.maps.Map(
document.getElementById("map"), {
center: new google.maps.LatLng(40.7127837, -74.0059413),
zoom: 11,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
// New York, NY, USA (40.7127837, -74.0059413)
// Newark, NJ, USA (40.735657, -74.1723667)
// Jersey City, NJ, USA (40.72815749999999, -74.07764170000002)
// Bayonne, NJ, USA (40.6687141, -74.11430910000001)
addMarker({
lat: 40.7127837,
lng: -74.0059413
}, "red", "New York is awesome!");
addMarker({
lat: 40.735657,
lng: -74.1723667
}, "green", "Newark is also cool!");
addMarker({
lat: 40.7281575,
lng: -74.0776417
}, "yellow", "Do not forget Jersey City!");
addMarker({
lat: 40.6687141,
lng: -74.1143091
}, "orange", "And not to mention Bayonne, too!");
}
google.maps.event.addDomListener(window, "load", initialize);
function addMarker(location, color, content) {
var infowindow = new google.maps.InfoWindow({
content: content
});
var marker = new google.maps.Marker({
position: location,
label: labels[labelIndex++ % labels.length],
icon: {
url: 'http://maps.google.com/mapfiles/ms/icons/' + color + '.png',
labelOrigin: new google.maps.Point(15, 10)
},
map: map
});
marker.addListener('click', function() {
infowindow.open(map, marker);
});
markers.push(marker);
}

Categories

Resources