Google Maps API V3: Exclude single marker from clustering - javascript

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

Related

variable in Jquery For Google Map

I have ajax success function like below
success: function(result) {
for (var i = 0; i < result['Result'].length; i++) {
if (result['Result'][i]['ClusterId'] == '2414040001') {
if (result['Result'][i]['UserLatitude'] != '' &&
result['Result'][i]['UserLatitude'] != null) {
window.UserLatitude = result['Result'][i][
'UserLatitude'
];
} else {
window.UserLatitude = '';
}
if (result['Result'][i]['UserLongitude'] != '' &&
result['Result'][i]['UserLongitude'] != null) {
window.UserLongitude = result['Result'][i][
'UserLongitude'
];
} else {
window.UserLongitude = '';
}
console.log("LAT:" + UserLatitude + "LONG:" +
UserLongitude);
}
}
const myLatLng = {
lat: UserLatitude,
lng: UserLongitude
};
console.log(myLatLng);
const map = new google.maps.Map(document.getElementById(
"googleMap"), {
zoom: 4,
center: myLatLng,
});
new google.maps.Marker({
position: {
lat: -33.890,
lng: 151.274
},
map,
title: "Hello World!",
});
}
I am getting latitude and longitude from remote server and want use it for Google Map.
Its working fine if I use const like below
const myLatLng = { lat: -33.890, lng: 151.274 };
but if I use variable for it, its giving me error like below
InvalidValueError: setCenter: not a LatLng or LatLngLiteral with finite coordinates: in property lat: not a number
I am not getting idea what is the problem and how I can solve it.
Thanks!
The response returned by the server might be string.Can you please try this code to parse the lat and long value to float lat and lng value using parseFloat() method from javascript.
// const myLatLng = { lat: UserLatitude, lng: UserLongitude };
// change above code to
const myLatLng = { lat: parseFloat(UserLatitude), lng: parseFloat(UserLongitude) };
console.log(myLatLng);
const map = new google.maps.Map(document.getElementById("googleMap"), {
zoom: 4,
center: myLatLng,
});
new google.maps.Marker({
position: {lat: -33.890, lng: 151.274},
map,
title: "Hello World!",
});

Google Maps API in a for loop, how to incorporate a info window?

So I have 4 maps all together on one page. I have them all working through the for loop. Now I need to add markers/ Infowindows any idea the best way to add that into the loop, thanks!
// array of lat and lng locations
let locations = [
{
lat:-33.91722,
lng:151.23064
},
{
lat:22.3193,
lng:114.1694
},
{
lat:22.3255,
lng:114.3532
},
{
lat:23.3532,
lng:115.1234
}
];
let elements = ['maps', 'map-rec-one', 'map-rec-two', 'map-rec-three']; // array of html element ids
window.addEventListener('load',
function() {
for (i = 0; i < elements.length; i++) {
initMap(locations[i], elements[i]);
console.log(elements[i]);
console.log(locations[i])}
}, false);
function initMap(location, element) {
console.log(location)
console.log(element)
map = new google.maps.Map(document.getElementById(element), {zoom:4, center: location});
}
One option would be to add the information for the markers to your array.
(if you want the same markers on each map, you can simplify the array or have a separate array for the markers)
let locations = [{
lat: -33.91722,
lng: 151.23064,
markers: [{
lat: -33.91722,
lng: 151.23064,
info: "this is a marker at -33.91722,151.23064"
}, {
lat: -33.8722,
lng: 151.03064,
info: "this is a marker at -33.8722,151.03064"
},
{
lat: -33.5722,
lng: 151.03064,
info: "this is a marker at -33.5722,151.03064"
}
]
},
{
lat: 22.3193,
lng: 114.1694,
markers: [{
lat: 22.3193,
lng: 114.1694,
info: "this is a marker at 22.3193,114.1694"
}]
},
{
lat: 22.3255,
lng: 114.3532
},
{
lat: 23.3532,
lng: 115.1234
}
];
Then in your initMap function, add those markers to the map:
function initMap(location, element, infowindow) {
console.log(location)
console.log(element)
map = new google.maps.Map(document.getElementById(element), {
zoom: 4,
center: location
});
if (location.markers) {
for (var i = 0; i < location.markers.length; i++) {
createMarker(location.markers[i], map, infowindow);
}
}
}
createMarker function:
function createMarker(location, map, infowindow) {
let marker = new google.maps.Marker({
position: location,
map: map
});
google.maps.event.addListener(marker, 'click', function(evt) {
infowindow.setContent(location.info);
infowindow.open(map, marker);
})
}
proof of concept fiddle
code snippet:
// The following example creates complex markers to indicate beaches near
// Sydney, NSW, Australia. Note that the anchor is set to (0,32) to correspond
// to the base of the flagpole.
function initialize() {
// array of lat and lng locations
let locations = [{
lat: -33.91722,
lng: 151.23064,
markers: [{
lat: -33.91722,
lng: 151.23064,
info: "this is a marker at -33.91722,151.23064"
}, {
lat: -33.8722,
lng: 151.03064,
info: "this is a marker at -33.8722,151.03064"
},
{
lat: -33.5722,
lng: 151.03064,
info: "this is a marker at -33.5722,151.03064"
}
]
},
{
lat: 22.3193,
lng: 114.1694,
markers: [{
lat: 22.3193,
lng: 114.1694,
info: "this is a marker at 22.3193,114.1694"
}]
},
{
lat: 22.3255,
lng: 114.3532
},
{
lat: 23.3532,
lng: 115.1234
}
];
let elements = ['maps', 'map-rec-one', 'map-rec-two', 'map-rec-three']; // array of html element ids
window.addEventListener('load',
function() {
for (i = 0; i < elements.length; i++) {
initMap(locations[i], elements[i], new google.maps.InfoWindow());
console.log(elements[i]);
console.log(locations[i])
}
}, false);
function initMap(location, element, infowindow) {
console.log(location)
console.log(element)
map = new google.maps.Map(document.getElementById(element), {
zoom: 4,
center: location
});
if (location.markers) {
for (var i = 0; i < location.markers.length; i++) {
createMarker(location.markers[i], map, infowindow);
}
}
}
function createMarker(location, map, infowindow) {
let marker = new google.maps.Marker({
position: location,
map: map
});
google.maps.event.addListener(marker, 'click', function(evt) {
infowindow.setContent(location.info);
infowindow.open(map, marker);
})
}
}
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#maps,
#map-rec-one,
#map-rec-two,
#map-rec-three {
height: 100%;
width: 25%;
float: right;
}
/* Optional: Makes the sample page fill the window. */
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
<!DOCTYPE html>
<html>
<head>
<title>Complex Marker Icons</title>
<script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initialize&libraries=&v=weekly" defer></script>
<!-- jsFiddle will insert css and js -->
</head>
<body>
<div id="maps"></div>
<div id="map-rec-one"></div>
<div id="map-rec-two"></div>
<div id="map-rec-three"></div>
</body>
</html>

Google Maps Infowindow issue after Geocode adaptation

I switched my code from the lat-lang system to the geocode API in order to resolve addresses, but unfortunately, the Google Maps Infowindows don't work properly. Only a few of them are displayed, with wrong information.
Here there is my code.
<script type="text/javascript">
if(document.getElementById("{idMap}")) {
let geocoder;
let map;
let locations = [
[ "Location 1" , "Via Pavia 57, 80021" ] ,
[ "Location 2" , "Via Palermo 24, 80021" ] ,
[ "Location 3" , "Via Milano 15, 80021" ] ,
];
function initializeMap() {
geocoder = new google.maps.Geocoder();
let infowindow = new google.maps.InfoWindow();
let bounds = new google.maps.LatLngBounds();
let mapSettings = {
zoomControl: false,
mapTypeControl: false,
scaleControl: false,
streetViewControl: false,
rotateControl: false,
fullscreenControl: false,
};
map = new google.maps.Map(document.getElementById("{idMap}"), mapSettings);
for (i = 0; i < locations.length; i++) {
codeAddress(locations[i][1], i, bounds);
}
}
function codeAddress(address, index, bounds) {
geocoder.geocode({ address: address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
let latLng = {
lat: results[0].geometry.location.lat(),
lng: results[0].geometry.location.lng(),
};
if (status == "OK") {
let marker = new google.maps.Marker({
position: latLng,
map: map,
icon: "https://maps.google.com/mapfiles/ms/icons/blue-dot.png",
});
bounds.extend(marker.position);
map.fitBounds(bounds);
map.panToBounds(bounds);
if(locations[0][index] && locations[0][index].length > 0) {
let infowindow = new google.maps.InfoWindow({
content: locations[0][index],
});
marker.addListener("click", function () {
infowindow.open(map, marker);
});
}
} else {
console.log(
"Geocode was not successful for the following reason: " + status
);
}
}
});
}
window.initMap = null;
window.initMap = initializeMap();
}
</script>
All the markers are correctly positioned, the issue is only related to the infoWindow.
I fixed the issue, passing the id from the marker to the location array, in this way it works:
let infowindow = new google.maps.InfoWindow({
content: locations[marker.id][1],
});

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

jQuery gmaps marker infowindow won't show on start

I have just a simple question about the jQuery Google Maps code.
I've added a marker to a map and the infowindow doesn't show up on start, only after mousehover.
Here is the code:
(function ($) {
var map;
var lat = XX.XXXXXX;
var lng = X.XXXXX;
var htmlcontent = 'CONTENT';
$(document).ready(function(){
if ( document.getElementById("map") ) {
map = new GMaps({
el: '#map',
lat: lat,
lng: lng,
zoomControl : true,
zoomControlOpt: {
style : 'SMALL',
position: 'TOP_LEFT'
},
panControl : true,
streetViewControl : false,
mapTypeControl: true,
overviewMapControl: true
});
var marker = map.addMarker({
lat: lat,
lng: lng,
title: 'THE TITLE',
infoWindow: {
content: htmlcontent
},
mouseover: function(e){
this.infoWindow.open(this.map, this);
}
});
marker.infoWindow.open(map.self, marker);
map.setCenter(XX.XXXXXX, X.XXXXXX);
};
});
})(jQuery);
So, this is the part where I have problems with:
marker.infoWindow.open(map.self, marker);
It worked well, a few weeks (or months) ago.
I will get this error in the console
infowindow.js:4 Uncaught TypeError: Cannot read property 'get' of undefined
and this warning
Google Maps API warning: NoApiKeys https://developers.google.com/maps/documentation/javascript/error-messages#no-api-keys
How to fix the infowindow of the marker?
Edit: I set the center of the marker individually because the popup of the marker isn't centered at all.
Edit2: Added API keys, no error or warning, but the infowindow of the marker won't show up at start
The google.maps.Map object is map.map:
code snippet:
(function($) {
var map;
var lat = 42;
var lng = -72;
var htmlcontent = 'CONTENT';
$(document).ready(function() {
if (document.getElementById("map")) {
map = new GMaps({
el: '#map',
lat: lat,
lng: lng,
zoomControl: true,
zoomControlOpt: {
style: 'SMALL',
position: 'TOP_LEFT'
},
panControl: true,
streetViewControl: false,
mapTypeControl: true,
overviewMapControl: true
});
var marker = map.addMarker({
lat: lat,
lng: lng,
title: 'THE TITLE',
infoWindow: {
content: htmlcontent
},
mouseover: function(e) {
this.infoWindow.open(this.map, this);
}
});
marker.infoWindow.open(map.map, marker);
map.setCenter(42, -72);
};
});
})(jQuery);
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://hpneo.github.io/gmaps/gmaps.js"></script>
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map"></div>

Categories

Resources