Google Maps. Multiple maps with multiple markers with content - javascript

I have this code to call multiple maps in one page, it's calling everything using arrays to make the code as short is possible.
from the question: Multiple googleMaps in one page with non sequential ID's
var coords = [
{lat: 53.647143, lng: -2.317803, zoom: 10},
{lat: 53.259065, lng: -4.417487, zoom: 7}
];
var markers = [];
var maps = [];
function initMap() {
for(var i = 0, length = coords.length; i < length; i++)
{
var point = coords[i];
var latlng = new google.maps.LatLng(point.lat, point.lng);
maps[i] = new google.maps.Map(document.getElementsByClassName('Gmap')[i], {
zoom: point.zoom,
center: latlng
});
markers[i] = new google.maps.Marker({
position: latlng,
map: maps[i]
});
}
}
This code runs using a callback once the google maps script is loaded and it's working very good, but it's displaying only one marker per map.
I need to add multiple markers on every map, I was thinking about include the markers coordinates inside the "coords" array:
var coords = [
{lat: 53.647143, lng: -2.317803, zoom: 10, marks: [
{mlat: 53.647143, mlng: -2.317803, mCont: "<p>aaa</p>"},
{mlat: 53.576524, mlng: -2.429149, mCont: "<p>bbb</p>"}
]},
{lat: 53.259065, lng: -4.417487, zoom: 7, marks: [
{mlat: 53.259065, mlng: -4.417487, mCont: "<p>ccc</p>"},
{mlat: 53.412303, mlng: -3.004262, mCont: "<p>ddd</p>"},
{mlat: 54.234574, mlng: -4.548636, mCont: "<p>eee</p>"}
]}
];
But I'm not sure how to implemented into the code to make it works, any ideas?
code running: https://jsfiddle.net/wfmztu8v/9/

There might be better ways to define your data. But with the existing format, this works:
function initMap() {
for (var i = 0, length = coords.length; i < length; i++) {
// create the map
var point = coords[i];
var latlng = new google.maps.LatLng(point.lat, point.lng);
maps[i] = new google.maps.Map(document.getElementsByClassName('map')[i], {
zoom: point.zoom,
center: latlng
});
// process the markers for the map
for (var j = 0; j < coords[i].marks.length; j++) {
if (!markers[i]) markers[i] = [];
if (!infowindow[i]) infowindow[i] = new google.maps.InfoWindow();
markers[i][j] = new google.maps.Marker({
position: {
lat: coords[i].marks[j].mlat,
lng: coords[i].marks[j].mlng
},
map: maps[i]
});
// open an infowindow when marker clicked
google.maps.event.addListener(markers[i][j], 'click', (function(map, content, infowindow) {
return function(e) {
infowindow.setContent(content);
infowindow.open(map, this);
}
})(maps[i], coords[i].marks[j].mCont, infowindow[i]));
}
}
}
updated fiddle
code snippet:
var coords = [{
lat: 53.647143,
lng: -2.317803,
zoom: 10,
marks: [{
mlat: 53.647143,
mlng: -2.317803,
mCont: "<p>aaa</p>"
},
{
mlat: 53.576524,
mlng: -2.429149,
mCont: "<p>bbb</p>"
}
]
},
{
lat: 53.259065,
lng: -4.417487,
zoom: 7,
marks: [{
mlat: 53.259065,
mlng: -4.417487,
mCont: "<p>ccc</p>"
},
{
mlat: 53.412303,
mlng: -3.004262,
mCont: "<p>ddd</p>"
},
{
mlat: 54.234574,
mlng: -4.548636,
mCont: "<p>eee</p>"
}
]
}
];
var markers = [];
var maps = [];
var infowindow = [];
function initMap() {
for (var i = 0, length = coords.length; i < length; i++) {
var point = coords[i];
var latlng = new google.maps.LatLng(point.lat, point.lng);
maps[i] = new google.maps.Map(document.getElementsByClassName('map')[i], {
zoom: point.zoom,
center: latlng
});
for (var j = 0; j < coords[i].marks.length; j++) {
if (!markers[i]) markers[i] = [];
if (!infowindow[i]) infowindow[i] = new google.maps.InfoWindow();
markers[i][j] = new google.maps.Marker({
position: {
lat: coords[i].marks[j].mlat,
lng: coords[i].marks[j].mlng
},
map: maps[i]
});
google.maps.event.addListener(markers[i][j], 'click', (function(map, content, infowindow) {
return function(e) {
infowindow.setContent(content);
infowindow.open(map, this);
}
})(maps[i], coords[i].marks[j].mCont, infowindow[i]));
}
}
}
initMap();
html,
body {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
#mapNorth {
height: 49%;
width: 98%;
float: top;
border: 1px solid black;
}
#mapSouth {
height: 49%;
width: 98%;
border: 1px solid black;
}
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div id="mapNorth" class="map"></div>
<div id="mapSouth" class="map"></div>

The problem is that your code put marker0 on map0 and marker1 to map1... you have to iterate second time for markers..
var coords = [
[{lat: 53.647143, lng: -2.317803, zoom: 10, marks: [
{mlat: 53.647143, mlng: -2.317803, mCont: "<p>aaa</p>"},
{mlat: 53.576524, mlng: -2.429149, mCont: "<p>bbb</p>"}
]
}],
[{lat: 53.259065, lng: -4.417487, zoom: 7, marks: [
{mlat: 53.259065, mlng: -4.417487, mCont: "<p>ccc</p>"},
{mlat: 53.412303, mlng: -3.004262, mCont: "<p>ddd</p>"},
{mlat: 54.234574, mlng: -4.548636, mCont: "<p>eee</p>"}
]
}]
];
var markers = [];
var maps = [];
var dot = [];
var dots = [];
function initMap() {
/* This will add all markers of coords[i] to maps[i] */
function placeMarkersOnMap(i) {
for (var x = 0, length1 = coords[i][0].marks.length; x < length1; x++) {
dots[x] = coords[i][0].marks[x];
dot[x] = new google.maps.LatLng(dots[x].mlat, dots[x].mlng);
markers[x] = new google.maps.Marker({
position: dot[x],
map: maps[i]
});
}
}
for (var i = 0, length = coords.length; i < length; i++) {
var point = coords[i];
console.log(point[0].lat)
var latlng = new google.maps.LatLng(point[0].lat, point[0].lng);
maps[i] = new google.maps.Map(document.getElementsByClassName('map')[i], {
zoom: point[0].zoom,
center: latlng
});
placeMarkersOnMap(i);
}
}
initMap();

Related

How to set value to object is array of object?

I tried something like this
<script charset="utf-8">
var request = new XMLHttpRequest();
// request.open("POST", "https://localhost:8443/control/jqxGeneralServicer?sname=JQGetListCustomerByCluster&deliveryClusterId=120120", false);
request.open("POST", "https://localhost:8443/control/jqxGeneralServicer?sname=JQGetListCustomerByCluster&deliveryClusterId=${deliveryCluster.deliveryClusterId}", false);
// ${deliveryCluster.deliveryClusterId}
request.setRequestHeader('Content-Type', 'application/json');
request.send(null);
var foo = request.responseText;
var json = JSON.parse(foo);
// console.log(json["results"][0]);
var labels = new Array();
var locations = new Array();
for(i = 0; i < json["results"].length; i++){
labels.push(json["results"][i]["fullName"]);
locacations["lng"] = json["results"][i]["longitude"];
locacations["lat"] = json["results"][i]["latitude"];
}
// console.log(labels) ;
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 = [
// "Cửa hàng Quang Anh",
// "Cửa hàng Quang Em",
// "Cửa hàng Hưng Thịnh",
// "Cửa hàng Cửa hàng Thành Hưng"];
var 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],
//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>
<div id="map" style="height: 400px; width: 100%; margin: 0px 10px 10px 10px;"></div>
Please guide me set value for var locations from json data source.
These line is not satisfy me (but I don't know how to change it)
for(i = 0; i < json["results"].length; i++){
labels.push(json["results"][i]["fullName"]);// this line is ok for variable `labels`
locacations["lng"] = json["results"][i]["longitude"]; // these lines is not ok
locacations["lat"] = json["results"][i]["latitude"]; // these lines is not ok.
}
//
The true format must be like the sample from Google Maps
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 }
];
Just push an object instead:
locations.push({lng: json['results'][i]['longitude'], lat: json['results'][i]['latitude']});
beware that you shouldn't use synchronous http requests.

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

How to remove multiple Circle for google map

I am trying to remove all the 4 circle from google map with a click of a button, but currently I can only remove one circle. Could anyone let me know how I can remove the multiple circle at once with a click of a button. Sorry I am new to this. Thanks in advance.
My code:
<input onclick="removecircle();" type=button value="Remove line">
<input onclick="addcircle();" type=button value="Restore line">
<div id="map"></div>
<script>
var cityCircle;
var citymap = {
chicago: {
center: {lat: 41.878, lng: -87.629},
population: 2714856
},
newyork: {
center: {lat: 40.714, lng: -74.005},
population: 8405837
},
losangeles: {
center: {lat: 34.052, lng: -118.243},
population: 3857799
},
vancouver: {
center: {lat: 49.25, lng: -123.1},
population: 603502
}
};
function initMap() {
// Create the map.
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: {lat: 37.090, lng: -95.712},
mapTypeId: 'terrain'
});
// Construct the circle for each value in citymap.
// Note: We scale the area of the circle based on the population.
for (var city in citymap) {
// Add the circle for this city to the map.
cityCircle = new google.maps.Circle({
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: 0.35,
map: map,
center: citymap[city].center,
radius: Math.sqrt(citymap[city].population) * 100
});
}
}
function addcircle(){
cityCircle.setMap(map);
}
function removecircle(){
cityCircle.setMap(null);
}
Image 1
Image 2
You need to keep references to the circles (and the map) in the global scope (where they will be accessible from HTML click listener functions). Then process through all the circles to either add or remove them from the map.
var circles = [];
var map;
function initMap() {
// Create the map.
map = new google.maps.Map(document.getElementById('map'), {
zoom: 3,
center: {
lat: 37.090,
lng: -95.712
},
mapTypeId: 'terrain'
});
// Construct the circle for each value in citymap.
// Note: We scale the area of the circle based on the population.
for (var city in citymap) {
// Add the circle for this city to the map.
var cityCircle = new google.maps.Circle({
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: 0.35,
map: map,
center: citymap[city].center,
radius: Math.sqrt(citymap[city].population) * 100
});
// keep reference to the circle
circles.push(cityCircle);
}
}
function addcircle() {
for (var i = 0; i < circles.length; i++) {
circles[i].setMap(map);
}
}
function removecircle() {
for (var i = 0; i < circles.length; i++) {
circles[i].setMap(null);
}
}
proof of concept fiddle
code snippet:
html,
body,
#map {
height: 100%;
margin: 0;
padding: 0;
width: 100%;
}
<input onclick="removecircle();" type=button value="Remove circles">
<input onclick="addcircle();" type=button value="Restore circles">
<script src="https://maps.googleapis.com/maps/api/js" type="text/javascript"></script>
<div id="map"></div>
<script>
var circles = [];
var map;
function initMap() {
// Create the map.
map = new google.maps.Map(document.getElementById('map'), {
zoom: 3,
center: {
lat: 37.090,
lng: -95.712
},
mapTypeId: 'terrain'
});
// Construct the circle for each value in citymap.
// Note: We scale the area of the circle based on the population.
for (var city in citymap) {
// Add the circle for this city to the map.
var cityCircle = new google.maps.Circle({
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: 0.35,
map: map,
center: citymap[city].center,
radius: Math.sqrt(citymap[city].population) * 100
});
circles.push(cityCircle);
}
}
function addcircle() {
for (var i = 0; i < circles.length; i++) {
circles[i].setMap(map);
}
}
function removecircle() {
for (var i = 0; i < circles.length; i++) {
circles[i].setMap(null);
}
}
google.maps.event.addDomListener(window, 'load', initMap);
var cityCircle;
var citymap = {
chicago: {
center: {
lat: 41.878,
lng: -87.629
},
population: 2714856
},
newyork: {
center: {
lat: 40.714,
lng: -74.005
},
population: 8405837
},
losangeles: {
center: {
lat: 34.052,
lng: -118.243
},
population: 3857799
},
vancouver: {
center: {
lat: 49.25,
lng: -123.1
},
population: 603502
}
};
</script>

Reutilize maps markers for weighted heatMaps

I'm using this functions to get markers via Ajax, and draw it in a map_canvas div. That works perfectly, and I'm trying to reuse the "gmarkers" variable to create a heatmap...with no luck. How can I create a heatmap with this data?
I prefer to use the same data I'm loading with this function weighting the heatmap by variable: llamados.
How can I start?
var gmarkers = [];
function initialize() {
var myOptions = {
zoom: 10,
center: mapCenter,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map_canvas'), myOptions);
current_zoom = map.getZoom();
var myControl = document.getElementById('descripcion');
map.controls[google.maps.ControlPosition.RIGHT_BOTTOM].push(myControl);
}
google.maps.event.addDomListener(window, 'load', initialize);
var infowindow = new google.maps.InfoWindow();
var bounds = new google.maps.LatLngBounds();
var marker, i;
var myLatLng;
function CreateMarker (obj, i) {
myLatLng = new google.maps.LatLng(obj['lat'], obj['lon']);
marker = new google.maps.Marker({
position: myLatLng,
animation: google.maps.Animation.DROP,
title: obj['nodo'],
llamados: obj['llamados'],
icon: obj['icono'],
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent('Nodo: ' + obj['nodo'] + '; Llamados: ' + obj['llamados']);
infowindow.open(map, marker);
}
})(marker, i));
gmarkers.push(marker);
}
function ejecutarAjax(){
$.ajax({
beforeSend: function() {
},
cache: false,
// data: params,
dataType: 'json',
timeout: 0,
type: 'POST',
url: 'traerLlamados.php',
success: function(data) {
if (data) {
var data = data;
var obj;
cantidad=Object.keys(data).length;
for(var i in data){
CreateMarker(data[i]);
};
}
else {
alert('No data');
}
},
});
}
Given your existing code, you should be able to add a heatmap to the map (after the markers are loaded) by doing:
var heatmapArray = [];
for (var i=0; i<gmarkers.length; i++) {
heatmapArray.push({location: gmarkers[i].getPosition(), weight: gmarkers[i].llamados});
}
var heatmap = new google.maps.visualization.HeatmapLayer({
data: heatmapArray
});
heatmap.setMap(map);
Proof of concept fiddle
Code snippet:
var gmarkers = [];
var mapCenter = new google.maps.LatLng(37.782, -122.447);
function initialize() {
var myOptions = {
zoom: 15,
center: mapCenter,
mapTypeId: google.maps.MapTypeId.SATELLITE
};
map = new google.maps.Map(document.getElementById('map_canvas'), myOptions);
current_zoom = map.getZoom();
var myControl = document.getElementById('descripcion');
map.controls[google.maps.ControlPosition.RIGHT_BOTTOM].push(myControl);
for (var i = 0; i < heatMapData.length; i++) {
// Translate into obj expected by CreateMarker
var obj = {
lat: heatMapData[i].location.lat(),
lon: heatMapData[i].location.lng(),
nodo: "nodo" + i,
llamados: heatMapData[i].weight,
icono: "http://maps.google.com/mapfiles/ms/micons/blue.png"
}
CreateMarker(obj, i);
}
var heatmapArray = [];
for (var i = 0; i < gmarkers.length; i++) {
heatmapArray.push({
location: gmarkers[i].getPosition(),
weight: gmarkers[i].llamados
});
}
var heatmap = new google.maps.visualization.HeatmapLayer({
data: heatmapArray
});
heatmap.setMap(map);
}
google.maps.event.addDomListener(window, 'load', initialize);
var infowindow = new google.maps.InfoWindow();
var bounds = new google.maps.LatLngBounds();
var marker, i;
var myLatLng;
function CreateMarker(obj, i) {
myLatLng = new google.maps.LatLng(obj['lat'], obj['lon']);
marker = new google.maps.Marker({
position: myLatLng,
animation: google.maps.Animation.DROP,
title: obj['nodo'],
llamados: obj['llamados'],
icon: obj['icono'],
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent('Nodo: ' + obj['nodo'] + '; Llamados: ' + obj['llamados']);
infowindow.open(map, marker);
}
})(marker, i));
gmarkers.push(marker);
}
google.maps.event.addDomListener(window, "load", initialize);
/* Data points defined as a mixture of WeightedLocation and LatLng objects */
var heatMapData = [{
location: new google.maps.LatLng(37.782, -122.447),
weight: 0.5
}, {
location: new google.maps.LatLng(37.782, -122.445),
weight: 1
}, {
location: new google.maps.LatLng(37.782, -122.443),
weight: 2
}, {
location: new google.maps.LatLng(37.782, -122.441),
weight: 3
}, {
location: new google.maps.LatLng(37.782, -122.439),
weight: 2
}, {
location: new google.maps.LatLng(37.782, -122.437),
weight: 10
}, {
location: new google.maps.LatLng(37.782, -122.435),
weight: 0.5
}, {
location: new google.maps.LatLng(37.785, -122.447),
weight: 3
}, {
location: new google.maps.LatLng(37.785, -122.445),
weight: 2
}, {
location: new google.maps.LatLng(37.785, -122.443),
weight: 5
}, {
location: new google.maps.LatLng(37.785, -122.441),
weight: 0.5
}, {
location: new google.maps.LatLng(37.785, -122.439),
weight: 1
}, {
location: new google.maps.LatLng(37.785, -122.437),
weight: 2
}, {
location: new google.maps.LatLng(37.785, -122.435),
weight: 3
}];
html,
body,
#map_canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?libraries=geometry,visualization"></script>
<div id="map_canvas"></div>

Google Maps API V3: Exclude single marker from clustering

I am using the google maps api and using grid clustering for the markers. I wanted to know if there is a way to exclude a single marker from clustering. I want a "You are here" marker that is always visible. I tried using a different array for just that marker and not including it the cluster function but that didn't work.
Does anyone have a solution for this?
Here is how i am doing the clustering
$(document).on('click', '#mapbut', function() {
var items, distances, you_are_here = [], markers_data = [], markers_data2 = [], fred, clust1, markss;
you_are_here.push({
lat : Geo.lat,
lng : Geo .lng,
animation: google.maps.Animation.DROP,
title : 'Your are here',
icon: {
path: google.maps.SymbolPath.CIRCLE,
scale: 10
},
infoWindow: {
content: '<p>You are Here</p>'
}
});
function loadResults (data) {
if (data.map.length > 0) {
items = data.map;
for (var i = 0; i < items.length; i++)
{
var item = items[i];
var distances = [];
var dist2;
if (item.Lat != undefined && item.Lng != undefined)
{
markers_data.push({
lat : item.Lat,
lng : item.Lng,
title : item.Site,
infoWindow: {
content: '<p>' + item.Site + '</p><p>' + Math.round(item.distance) + ' miles away</p>'
}
});
}
}
}
map.addMarkers(markers_data);
map = new GMaps({
el: '#map',
lat: Geo.lat,
lng: Geo.lng,
zoom: 10,
mapTypeControl: false,
zoomControl: true,
zoomControlOptions: {
position: google.maps.ControlPosition.LEFT_CENTER
},
markerClusterer: function(map) {
options = {
gridSize: 50
}
clust1 = new MarkerClusterer(map,[], options);
return clust1;
},
scaleControl: true,
streetViewControl: false
});
map.addMarkers(you_are_here);
The GMaps clusters all the markers you add to it with the addMarker method (if you provide a MarkerClusterer).
One option: add your "special" marker (the one that you don't want clustered) to the map manually, so it isn't added to the MarkerClusterer:
The GMaps.map property is a reference to the Google Maps Javascript API v3 map object. So this will add a marker to the map without letting the GMaps library know about it:
you_are_here = new google.maps.Marker({
position: {lat: Geo.lat,lng: Geo.lng},
animation: google.maps.Animation.DROP,
title: 'Your are here',
icon: {
path: google.maps.SymbolPath.CIRCLE,
scale: 10
},
map: map.map
});
proof of concept fiddle
code snippet:
var Geo = {
lat: 40.7281575,
lng: -74.07764
};
$(document).on('click', '#mapbut', function() {
var items, distances, you_are_here = [],
markers_data = [],
markers_data2 = [],
fred, clust1, markss;
function loadResults(data) {
if (data.map.length > 0) {
items = data.map;
for (var i = 0; i < items.length; i++) {
var item = items[i];
var distances = [];
var dist2;
if (item.Lat != undefined && item.Lng != undefined) {
markers_data.push({
lat: item.Lat,
lng: item.Lng,
title: item.Site,
infoWindow: {
content: '<p>' + item.Site + '</p><p>' + Math.round(item.distance) + ' miles away</p>'
}
});
}
}
}
map = new GMaps({
el: '#map',
lat: Geo.lat,
lng: Geo.lng,
zoom: 8,
mapTypeControl: false,
zoomControl: true,
zoomControlOptions: {
position: google.maps.ControlPosition.LEFT_CENTER
},
markerClusterer: function(map) {
options = {
gridSize: 50,
imagePath: "https://cdn.rawgit.com/googlemaps/v3-utility-library/master/markerclustererplus/images/m"
}
clust1 = new MarkerClusterer(map, [], options);
return clust1;
},
scaleControl: true,
streetViewControl: false
});
map.addMarkers(markers_data);
you_are_here = new google.maps.Marker({
position: {
lat: Geo.lat,
lng: Geo.lng
},
animation: google.maps.Animation.DROP,
title: 'Your are here',
icon: {
path: google.maps.SymbolPath.CIRCLE,
scale: 10
},
infoWindow: {
content: '<p>You are Here</p>'
},
map: map.map
});
// map.addMarkers(you_are_here);
}
loadResults(data);
});
var data = {
map: [{
Lat: 40.7127837,
Lng: -74.005941,
Site: "New York, NY",
distance: 1
}, {
Site: "Newark, NJ",
Lat: 40.735657,
Lng: -74.1723667,
distance: 2
}]
};
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"></script>
<script src="https://rawgit.com/HPNeo/gmaps/master/gmaps.js"></script>
<script src="https://cdn.rawgit.com/googlemaps/v3-utility-library/master/markerclustererplus/src/markerclusterer.js"></script>
<input id="mapbut" type="button" value="map" />
<div id="map"></div>
To get around this is relatively simple, just after I send the markers array to MarkerClusterer I then add my location.
// Setup cluster markers
var markerCluster = new MarkerClusterer( gmap.map, options )
// add my location
gmap.addMarker({
lat: data.latitude,
lng: data.longitude
...
})
Thanks

Categories

Resources