How to add marker clusterer into googlemaps - javascript

I'm new to this google-maps and javascript, I have go through these examples.But I still no idea how to apply it into my codes, It doesn't works.Hope someone can help me.Thank you.
// this variable will collect the html which will eventually be placed in the side_bar
var side_bar_html = "";
// arrays to hold copies of the markers and html used by the side_bar
// because the function closure trick doesnt work there
var gmarkers = [];
// A function to create the marker and set up the event window
function createMarker(point,name,html) {
var marker = new GMarker(point);
GEvent.addListener(marker, "click", function() {
marker.openInfoWindowHtml(html);
});
// save the info we need to use later for the side_bar
gmarkers.push(marker);
// add a line to the side_bar html
side_bar_html += '<a href="javascript:myclick(' + (gmarkers.length-1) + ')">' + name + '<\/a><br>';
return marker;
}
// This function picks up the click and opens the corresponding info window
function myclick(i) {
GEvent.trigger(gmarkers[i], "click");
}
// create the map
var map = new GMap2(document.getElementById("map"));
map.addControl(new GLargeMapControl());
map.addControl(new GMapTypeControl());
map.setCenter(new GLatLng( 43.907787,-79.359741), 8);
// add the points
var point = new GLatLng(43.65654,-79.90138);
var marker = createMarker(point,"This place","Some stuff to display in the<br>First Info Window")
map.addOverlay(marker);
var point = new GLatLng(43.91892,-78.89231);
var marker = createMarker(point,"That place","Some stuff to display in the<br>Second Info Window")
map.addOverlay(marker);
var point = new GLatLng(43.82589,-78.89231);
var marker = createMarker(point,"The other place","Some stuff to display in the<br>Third Info Window")
map.addOverlay(marker);
// put the assembled side_bar_html contents into the side_bar div
document.getElementById("side_bar").innerHTML = side_bar_html;
}
The sidebar is made next to the google-maps.Hope someone can take a look on my code.

The documentation you got there is pretty good actually.
Let me know to simplify it a bit more.
So to get clusterer going you'll need the following bits and pieces.
Your project will have to import the markerclusterer.js file.
You need an array of markers.
You need to instantiate the MarkerClusterer object.
That is all, straight forward.
1: Instantiation of markers
I can see from the code you have already done it.
var marker = new google.maps.Marker(
{
position: myLatLng,
map: map,
title: '1111'
});
2: Building an array of markers
Nothing much here. Basically you declare an [] object and push the markers into it.
var markers = [ marker, marker2, marker3 ];
3: Instantiate the MarkerClusterer object
I guess the only challenging part is this one. As mentioned before, you'll new to import the markerclusterer.js file.
Build an object to hold whatever configuration that is needed for the MarkerClusterer object and instantiate it.
markerCluster = new MarkerClusterer(map, markers, {
imagePath: 'https://googlemaps.github.io/js-marker-clusterer/images/m',
gridSize: 10,
minimumClusterSize: 2
});
Here is an example;
Clusterer

Related

Google maps - reuse single infoWindow for multiple markers

I have multiple markers and currently when more than one infoWindow is clicked, the other already-opened infoWindows stay open, cluttering the map. I would prefer it if I could simply reuse a single infoWindow, move it and update it's content. This is what I am attempting to do below:
var info = new SnazzyInfoWindow ();
/*
* Loop through each item in the 'features' array, including info windows, and display the marker
*/
features.forEach(function (feature) {
var marker = new google.maps.Marker({
position: feature.position,
icon: icons[feature.type].icon,
map: map
});
var infoContent = feature.contentImage + feature.content;
marker.addListener('click', function() {
infoCallback(infoContent, marker);
});
});
function infoCallback(infoContent, marker) {
return function() {
info.close();
info.setContent(infoContent)
info.open(map, marker);
};
};
However I am receiving the error Cannot read property 'placement' of undefined and can't seem to figure out what's wrong here.
Note that I am using the "Snazzy Info Window" plugin, but I think the same would apply to the stock infoWindow.
Yes. Inside the onClick function, when marker.addListener('click' is being executed, you don't have feature/marker. The variables are not what they were when the foreach was executed.
One trick I mostly use, is to make an array of the marker objects. Inside the onClick you search for the 'this' marker inside the array.
Something like this:
var markers = []; // store the markers in this array
features.forEach(function (feature) {
var marker = new google.maps.Marker({
position: feature.position,
icon: icons[feature.type].icon,
map: map
});
markers.push(marker);
marker.addListener('click', function() {
// first find out which marker was clicked on
var index = markers.indexOf(this); // this represents the marker that was clicked on
// index should be the same index as the index for features.
var feature = features[index];
var marker = markers[index];
var infoContent = feature.contentImage + feature.content;
// now we can call infoCallback.
infoCallback(infoContent, marker);
});
});

Multiple markers with info windows map error

I have this working map https://jsfiddle.net/m9ugbc7h/4/ then i tryed to integrate multiple markers with info windows following step by step this tutorial http://wrightshq.com/playground/placing-multiple-markers-on-a-google-map-using-api-3/ so now i got this new version of the map https://jsfiddle.net/m9ugbc7h/5/ but it doesn't work
Here the description how i think the added code works
This is the text for two info windows in order
var infoWindowContent = [
['<div class="info_content">' +
'<h3>Ventura</h3>' +
'<p>Ventura P</p>' +
'</div>'],
['<div class="info_content">' +
'<h3>Selvatica</h3>' +
'<p>Selvatica p</p>' +
'</div>']
];
This adds a number to every marker listed before
// Loop through our array of markers & place each one on the map
for( i = 0; i < markers.length; i++ ) {
var position = new google.maps.LatLng(markers[i][1], markers[i][2]);
bounds.extend(position);
marker = new google.maps.Marker({
position: position,
map: map,
title: markers[i][0]
});
And this one asigns text 1 to marker 1, text 2 to marker 2, etc.
// Allow each marker to have an info window
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infoWindow.setContent(infoWindowContent[i][0]);
infoWindow.open(map, marker);
}
})(marker, i));
You have few issues with the code:
First
Console error google is not defined caused by:
var bounds = new google.maps.LatLngBounds();
at the top of the file before google js is loaded. Move it inside jQuery(document).ready(function($){:
jQuery(document).ready(function($){
bounds = new google.maps.LatLngBounds();
Second
// Loop through our array of markers & place each one on the map
Why? They are already placed on the map, you just want to attach them InfoWindow:
//marker = new google.maps.Marker({
// position: position,
// map: map,
// title: markers[i][0]
//});
var marker = markers[i];
In the above code is the root of your problem (info windows not showing up): you are creating new Marker object instead of using the existing one from the markers array.
Third
Console error: too much recursion
caused by:
// Automatically center the map fitting all markers on the screen
map.fitBounds(bounds);
The issue with this one is most probably that bounds are undefined at this moment. Not sure why, but too much recursion is usualy caused by that. I have commented that out, so you will have to take a look how to pass valid value in fitBounds.
Fourth
You have sintax error here:
var infoWindow = new google.maps.InfoWindow(), marker, i;
You probably meant:
var infoWindow = new google.maps.InfoWindow();
Working fiddle: https://jsfiddle.net/m9ugbc7h/7/

google maps v3 open infowindow on click of external html link

Wonder if anyone can help me, I have setup a google map all works nicely. The only thing I cant work out how to do is to open an info window based on ID from an external html link that's not in the JS.
function initialize() {
// Create the map
// No need to specify zoom and center as we fit the map further down.
var map = new google.maps.Map(document.getElementById("map"), {
mapTypeId: google.maps.MapTypeId.ROADMAP,
disableDefaultUI: true
});
infowindow = new google.maps.InfoWindow();
// Custom markers
var icon = "img/marker.png";
// Define the list of markers.
// This could be generated server-side with a script creating the array.
var markers = [
{ val:0, lat: -40.149049, lng: 172.033095, title: "Title", html: "<div style='text-align:left'><h4 style='color:#0068a6;font-size:16px;margin:0px 0px 10px 0px;'>Title</h4><strong>Telephone</strong><br /><br />Address</div>" },
{ val:1, lat: -41.185765, lng: 174.827516, title: "Title", html: "<div style='text-align:left'><h4 style='color:#0068a6;font-size:16px;margin:0px 0px 10px 0px;'>Title</h4><strong>Telephone</strong><br /><br />Address</div>" },
];
// Create the markers ad infowindows.
for (index in markers) addMarker(markers[index]);
function addMarker(data) {
// Create the marker
var marker = new google.maps.Marker({
position: new google.maps.LatLng(data.lat, data.lng),
map: map,
title: data.title,
icon: icon,
id: data.val
});
// Create the infowindow with two DIV placeholders
// One for a text string, the other for the StreetView panorama.
var content = document.createElement("DIV");
var title = document.createElement("DIV");
title.innerHTML = data.html;
content.appendChild(title);
// Open the infowindow on marker click
google.maps.event.addListener(marker, "click", function() {
infowindow.setContent(content);
infowindow.open(map, this);
map.setCenter(this.position);
console.log(this.id);
});
}
// Zoom and center the map to fit the markers
// This logic could be conbined with the marker creation.
// Just keeping it separate for code clarity.
var bounds = new google.maps.LatLngBounds();
for (index in markers) {
var data = markers[index];
bounds.extend(new google.maps.LatLng(data.lat, data.lng));
}
map.fitBounds(bounds);
}
<p id="1">link to open marker</p>
Any help would be gratefully appreciated
Richard :)
The Golden Goose
Then in your js have a function to open the infowindow (such as show()) which takes the properties from that link (opening id 7).
function show(id){
myid = id;
if(markers[myid]){
map.panTo(markers[myid].getPoint());
setTimeout('GEvent.trigger(markers[myid], "click")',500);
map.hideControls();
}
}
That's the function I used previously with one of the marker managers from v2. You have to make sure you set an id for each marker as you set it and then you can call it.
The one thing I made sure of (to simplify matters) was to make sure the map marker set/array was exactly the same as the sql result I used on the page. That way, using id's was a piece of cake.

How to set google map marker by latitude and longitude and provide information bubble

The following sample code provided by google maps api
var geocoder;
var map;
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(40.77627, -73.910965);
var myOptions = {
zoom: 8,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
}
the following only shows google map of the location without a marker.
I was wondering how I can place a marker by giving latitude/longitude parameters?
And how is it possible to store my own information pulled from a database on that marker?
Here is a JSFiddle Demo that shows you how to set a google map marker by Lat Lng and also when click would give you an information window (bubble):
Here is our basic HTML with 3 hyperlinks when clicked adds a marker onto the map:
<div id="map_canvas"></div>
<a href='javascript:addMarker("usa")'>Click to Add U.S.A</a><br/>
<a href='javascript:addMarker("brasil")'>Click to Add Brasil</a><br/>
<a href='javascript:addMarker("argentina")'>Click to Add Argentina</a><br/>
First we set 2 global variables. one for map and another an array to hold our markers:
var map;
var markers = [];
This is our initialize to create a google map:
function initialize() {
var latlng = new google.maps.LatLng(40.77627, -73.910965);
var myOptions = {
zoom: 1,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
}
We then create 3 lat lng locations where we would like to place our markers:
var usa = new google.maps.LatLng(37.09024, -95.712891);
var brasil = new google.maps.LatLng(-14.235004, -51.92528);
var argentina = new google.maps.LatLng(-38.416097, -63.616672);
Here we create a function to add our markers based on whatever is passed onto it. myloc will be either usa, brasil or argentina and we then create the marker based on the passed param. With in the addMarker function we check and make sure we don't create duplicate marker on the map by calling the for loop and if we the passed param has already been created then we return out of the function and do nothing, else we create the marker and push it onto the global markers array. After the marker is created we then attach an info window with it's associated marker by doing markers[markers.length-1]['infowin'] markers.length-1 is just basically getting the newly pushed marker on the array. Within the info window we set the content using html. This is basically the information you put into the bubble or info window (it can be weather information which you can populate using a weather API and etc). After info window is attached we then attach an onclick event listener using the Google Map API's addListener and when the marker is clicked we want to open the info window that is associated with it by calling this['infowin'].open(map, this) where the map is our global map and this is the marker we are currently associating the onclick event with.
function addMarker(myloc) {
var current;
if (myloc == 'usa') current = usa;
else if (myloc == 'brasil') current = brasil;
else if (myloc == 'argentina') current = argentina;
for (var i = 0; i < markers.length; i++)
if (current.lat() === markers[i].position.lat() && current.lng() === markers[i].position.lng()) return;
markers.push(new google.maps.Marker({
map: map,
position: current,
title: myloc
}));
markers[markers.length - 1]['infowin'] = new google.maps.InfoWindow({
content: '<div>This is a marker in ' + myloc + '</div>'
});
google.maps.event.addListener(markers[markers.length - 1], 'click', function() {
this['infowin'].open(map, this);
});
}
When all is done we basically attach window.onload event and call the initialize function:
window.onload = initialize;

Google Maps API Sidebar

I'm adding markers and sidebar this way:
<script type="text/javascript">
//<![CDATA[
if (GBrowserIsCompatible()) {
// this variable will collect the html which will eventually be placed in the side_bar
var side_bar_html = "";
// arrays to hold copies of the markers and html used by the side_bar
// because the function closure trick doesnt work there
var gmarkers = [];
// A function to create the marker and set up the event window
function createMarker(point,name,html) {
var marker = new GMarker(point);
GEvent.addListener(marker, "click", function() {
marker.openInfoWindowHtml(html);
});
// save the info we need to use later for the side_bar
gmarkers.push(marker);
// add a line to the side_bar html
side_bar_html += '<li><a href="javascript:myclick(' + (gmarkers.length-1) + ')">' + name + '<\/a><\/li>';
return marker;
}
// This function picks up the click and opens the corresponding info window
function myclick(i) {
GEvent.trigger(gmarkers[i], "click");
GEvent.trigger(gmarkers2[i], "click");
}
// create the map
var map = new GMap2(document.getElementById("map"));
map.addControl(new GLargeMapControl());
map.addControl(new GMapTypeControl());
map.setCenter(new GLatLng( 52.898962,-8.21228), 7);
// add the points
var point = new GLatLng( 53.357826,-6.28418 );
var marker = createMarker(point,"Ashgrove Interparts Ltd.","<strong>Ashgrove Interparts Ltd.</strong><br>Kill Avenue.<br>Dunlaoire.<br>Co Dublin.<br>Tel; 01-2805063.<br>Contact; Mr Dermot Kelly.<br>Dublin Area")
map.addOverlay(marker);
var point = new GLatLng( 53.285845,-6.158266 );
var marker = createMarker(point,"Abbey Service Station.","<strong>Abbey Service Station.</strong><br>Abbey Road.<br>Monkstown.<br>Co. Dublin.<br>Tel; 01-2809626.<br>Contact; George/Kay.")
map.addOverlay(marker);
var point = new GLatLng( 53.340508,-6.228905 );
var marker = createMarker(point,"A & D Motorfactors.","<strong>A & D Motorfactors.</strong><br>Cromwellsfort Rd,<br>Dublin 12.<br>Tel; 01-460-1808.<br>Contact; Aiden/Ed.")
map.addOverlay(marker);
var point2 = new GLatLng( 53.440508,-6.238905 );
var marker2 = createMarker(point2,"test","<strong>A & D Motorfactors.</strong><br>Cromwellsfort Rd,<br>Dublin 12.<br>Tel; 01-460-1808.<br>Contact; Aiden/Ed.")
map.addOverlay(marker);
// put the assembled side_bar_html contents into the side_bar div
document.getElementById("side_bar").innerHTML = side_bar_html;
}
else {
alert("Sorry, the Google Maps API is not compatible with this browser");
}
//]]>
</script>
Now got question. How to extend it and make possible to add different markers to differend elements?
I am assuming that what you are trying to do is to differentiate your sets of markers, but use your common myclick handler code to show the appropriate info window for the marker.
There are a few ways you could do this. It looks like you were wanting to have a separate arrays of markers for each city because you have referenced a gmarkers2 array in your myclick handler. This is not going to work because you are creating the markers using the same handler function and the index wont work for both arrays.
So you either need a createMarker function that adds the new marker to the appropriate marker array and specifies a click handler that uses that array or you can use the same marker array and just change createMarker to update separate side_bar_html variables to store the reference url.
I have hacked together an example (based on your source) that uses the second approach. Please let me know if this isn't what you are trying to do.
N.B. In my sample, I stuck the "side bar" below the map.

Categories

Resources