Google Maps V3 - Remove all Markers - javascript

I want with google maps v3 that if you zoom-in higher than 15 the map show the marker locations but when you zoom-out i want to hide the markers. I can't find any function to do this. Nothing has worked for me so far.
So this is my script:
<script type="text/javascript">
function initialize() {
var mapOptions = {
zoom: 15,
center: new google.maps.LatLng(52.429236, 6.281255),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
setMarkers(map, points);
google.maps.event.addListener(map, 'zoom_changed', function()
{
if (map.getZoom() > 15) {
setMarkers(map, points);
} else {
hideMarkers(map, points);
}
});
}
var points = [
['Location 1', 52.420891, 6.280204],
['Location 2', 52.420125, 6.279131],
['Location 3', 52.420125, 6.240125]
];
function setMarkers(map, locations) {
var image = new google.maps.MarkerImage('../images/map/beachflag.png',
new google.maps.Size(20, 32),
new google.maps.Point(0,0),
new google.maps.Point(0, 32));
var shadow = new google.maps.MarkerImage('../images/map/beachflag_shadow.png',
new google.maps.Size(37, 32),
new google.maps.Point(0,0),
new google.maps.Point(0, 32));
var shape = {
coord: [1, 1, 1, 20, 18, 20, 18 , 1],
type: 'poly'
};
for (var i = 0; i < locations.length; i++) {
var point = locations[i];
var myLatLng = new google.maps.LatLng(point[1], point[2]);
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
shadow: shadow,
icon: image,
shape: shape,
title: point[0]
});
}
}
function hideMarkers(map, locations) {
/* Remove All Markers */
console.log("Remove All Markers");
}
</script>
Please can anybody help me whith this?

I modified your code. I am keeping the reference of all markers in an array. and inside hideMarkers i am setting their map as null to remove them from map.
function initialize() {
var mapOptions = {
zoom : 15,
center : new google.maps.LatLng(52.429236, 6.281255),
mapTypeId : google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
var markers = setMarkers(map, access_points);
google.maps.event.addListener(map, 'zoom_changed', function() {
if (map.getZoom() > 15) {
setMarkers(map, access_points);
}
else {
hideMarkers(map, access_points, markers);
}
});
}
var access_points = [ [ 'Location 1', 52.420891, 6.280204 ], [ 'Location 2', 52.420125, 6.279131 ], [ 'Location 3', 52.420125, 6.240125 ] ];
function setMarkers(map, locations) {
var markers= [];
var image = new google.maps.MarkerImage('../images/map/beachflag.png', new google.maps.Size(20, 32), new google.maps.Point(0, 0), new google.maps.Point(0,
32));
var shadow = new google.maps.MarkerImage('../images/map/beachflag_shadow.png', new google.maps.Size(37, 32), new google.maps.Point(0, 0),
new google.maps.Point(0, 32));
var shape = {
coord : [ 1, 1, 1, 20, 18, 20, 18, 1 ],
type : 'poly'
};
for ( var i = 0; i < locations.length; i++) {
var access_point = locations[i];
var myLatLng = new google.maps.LatLng(access_point[1], access_point[2]);
var marker = new google.maps.Marker({
position : myLatLng,
map : map,
shadow : shadow,
icon : image,
shape : shape,
title : access_point[0],
zIndex : access_point[3]
});
markers.push(marker);
}
return markers;
}
function hideMarkers(map, locations, markers) {
/* Remove All Markers */
while(markers.length){
markers.pop().setMap(null);
}
console.log("Remove All Markers");
}

The easiest way is probably to modify your code slightly, so that your markers are contained in an array that's accessible to both the setMarkers and hideMarkers functions. You can then use the setMap method of the Marker class to add/remove the marker from your map (pass null to setMap to remove the marker from the map):
var markers = [];
function createMarkers(/* some args */) {
// Create your markers, and add each one to the `markers` array
}
function setMarkers() {
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(yourMap); //Add the marker to the map
}
}
function hideMarkers() {
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(null); //Remove the marker from the map
}
}
This approach also means that you don't recreate all your Marker instances every time you want to show them.

Related

What will make google maps api clusters not work correctly?

I am looking for help to understand why my customized google maps api map will not work with marker clusters. Below is the section of code I am using to coordinate markers on the map but I cannot get them to cluster.
With this map there is a marker that shows the user where they are and there are multiple markers with the setup as restaurant below (ex: theaters, shops, etc) to show users things around them and I am looking to get the restaurants to cluster together as well as other points that are similar but the clustering will not group.
<script>
if(output.restaurantmsg == "ok") {
var image = {
url: 'img/Mobs/FK.png',
// This marker is 20 pixels wide by 32 pixels high.
size: new google.maps.Size(35, 32),
// The origin for this image is (0, 0).
origin: new google.maps.Point(0, 0),
// The anchor for this image is the base of the flagpole at (0, 32).
anchor: new google.maps.Point(0, 32)
};
var shape = {
coords: [1, 1, 1, 20, 18, 20, 18, 1],
type: 'poly'
};
var restaurantslist = new Array();
for (var i = 0; i < restaurantmaplistname.length; i++) {
restaurantslist[i] = new Array();
restaurantslist[i][0] = restaurantmaplistname[i];
restaurantslist[i][1] = parseFloat(restaurantmaplistlat[i]);
restaurantslist[i][2] = parseFloat(restaurantmaplistlng[i]);
restaurantslist[i][3] = i+1;
restaurantslist[i][4] = restaurantmaplistcontent[i];
}
//alert(dealslist);
for (var i = 0; i < restaurantslist.length; i++) {
var restaurantli = restaurantslist[i];
//alert(dealli[1]+'-'+dealli[2]+'-'+(typeof dealli[1])+'-'+typeof dealli[2]);
var markers = locations.map(function(lat: restaurantli[1], lng: restaurantli[2], ) {
var marker = new google.maps.Marker({
position: {lat: restaurantli[1], lng: restaurantli[2]},
map: map,
icon: image,
animation: google.maps.Animation.DROP,
shape: shape,
title: restaurantli[0],
zIndex: restaurantli[3]
});
var infowindow = new google.maps.InfoWindow();
var content = restaurantli[4];
google.maps.event.addListener(marker,'click', (function(marker,content,infowindow){
return function() {
infowindow.setContent(content);
infowindow.open(map,marker);
};
})(marker,content,infowindow));
return marker;
});
}
var markerCluster = new MarkerClusterer(map, markers, {
imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m'
});
}
var locations = [{
lat: restaurantli[1],
lng: restaurantli[2],
info: "marker 1"
}, ];
google.maps.event.addDomListener(window, "load", initMap);
</script>

Google Maps v3: plot different sets of markers

I am trying to plot on a google map a set of fixed markers and a marker for the user position. For these two sets of markers I would like to use a different image for the marker, however something weird is happening: when loading the page, the "fixed" markers get plotted properly but then immediately one disappears (the last one in the array) and then the user position shows up. In addition, the first fixed location gets the user location marker image, and the user positioning marker gets the image of the fixed markers. Ideally, the locations in the array will be plotted entirely (all 4) and with red_dot.png image on the marker, and the user positioning with the bluedot_retina.png on the marker.
It's really strange and I am struggling figuring out what is the root cause. Appreciate any help with this issue. thanks!
<script>
var locations = [
['location a', 37.60756088, -122.42793323],
['location b', 37.759736, -122.426957],
['location c', 37.752950, -122.438458],
['location d', 37.763128, -122.457942]
];
var map;
var i;
var marker;
var google_lat = 37.757996;
var google_long = -122.404479;
var myLatlng = new google.maps.LatLng(google_lat, google_long);
//google.maps.visualRefresh = true;
function initialize() {
var mapOptions = {
zoom: 12,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
var image_dot = new google.maps.MarkerImage(
'images/red_dot.png',
null, // size
null, // origin
new google.maps.Point( 8, 8 ), // anchor (move to center of marker)
new google.maps.Size( 8, 8 ) // scaled size (required for Retina display icon)
);
marker = new google.maps.Marker({
flat: true,
position: myLatlng,
icon: image,
optimized: false,
map: map,
visible: true,
title: 'I might be here'
});
setMarkers(map, locations);
} //initialize();
function setMarkers(map, locations) {
for (var i = 0; i < locations.length; i++) {
var beach = locations[i];
var myLatLng1 = new google.maps.LatLng(beach[1], beach[2]);
marker = new google.maps.Marker({
position: myLatLng1,
icon: image_dot,
map: map
});
}
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
<script type="text/javascript">
var Tdata;
var image = new google.maps.MarkerImage(
'images/bluedot_retina.png',
null, // size
null, // origin
new google.maps.Point( 8, 8 ), // anchor (move to center of marker)
new google.maps.Size( 17, 17 ) // scaled size (required for Retina display icon)
);
var userMarker = new google.maps.Marker({icon: image});
//var userMarker = new google.maps.Marker({icon: 'images/bluedot_retina.png'});
$.ajax({
method : "GET",
url: "get_location.php",
success : function(data){
Tdata=JSON.parse(data);
// console.log(data.lat);
console.log(Tdata.lat);
myFunction();
}
});
function myFunction(){
var interval = setInterval(function() {
$.get("get_location.php", function(Tdata) {
var JsonObject= JSON.parse(Tdata);
google_lat = JsonObject.lat;
google_long = JsonObject.long;
console.log(google_lat, google_long);
// $('#data').html('google_lat, google_long');
myLatlng = new google.maps.LatLng(google_lat, google_long);
//marker.setPosition(myLatlng);
userMarker.setPosition(myLatlng);
userMarker.setMap(map);
//map.setCenter(myLatlng);
});
}, 1000);
}
</script>
marker is a global variable. You are using it for both all of your locations and your user's position marker. Don't do that, assign unique (or local) names to the two classes of markers.
var Tdata;
var userMarker = new google.maps.Marker({icon: URL/to/custom/icon/for/user});
$.ajax({
method : "GET",
url: "get_location.php",
success : function(data){
Tdata=JSON.parse(data);
// console.log(data.lat);
console.log(Tdata.lat);
myFunction();
}
});
function myFunction(){
var interval = setInterval(function() {
$.get("get_location.php", function(Tdata) {
var JsonObject= JSON.parse(Tdata);
google_lat = JsonObject.lat;
google_long = JsonObject.long;
console.log(google_lat, google_long);
// $('#data').html('google_lat, google_long');
myLatlng = new google.maps.LatLng(google_lat, google_long);
userMarker.setPosition(myLatlng);
userMarker.setMap(map);
map.setCenter(myLatlng);
});
}, 1000);
}

Setting the content for each marker Google Maps

Need a quick help with setting up the content for each marker that I'm creating
I'm looping through my Locations Obj that holds Lat,Lng for each marker (locationObj),
the content for each marker is been hold by other obejct (PermutationObj).
example:
locationObj-- > {"Lat":"34.163291","Lng":"-118.685123"} etc....
PermutationObj -- > ElectronicPopContent,LocationName
The thing is I'm getting for all the markers that I'm displaying on the map the first content and location name from the PermutationObj.
How can I fix it???
JS Code:
var locationObj;
var PermutationObj;
var map;
var mapOptions;
var shape = {
coord: [1, 1, 1, 20, 18, 20, 18, 1],
type: 'poly'
};
function setMap(locationList, permutation) {
// List of Lat,Lng
locationObj = $.parseJSON(locationList);
PermutationObj = $.parseJSON(permutation);
var qMapTypeId = google.maps.MapTypeId.SATELLITE
var LatLngCenter = new google.maps.LatLng(34.163291, -118.685123);
var mapOptions = {
zoom: 4,
center: LatLngCenter,
mapTypeControl: true,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
}
}
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
var bounds = new google.maps.LatLngBounds();
for (i in locationObj) {
var LatLngPair = new google.maps.LatLng(locationObj[i]["Lat"], locationObj[i]["Lng"]);
bounds.extend(LatLngPair);
map.fitBounds(bounds);
// for (j in PermutationObj) {
// // var image = PropObj[j]["ElectroincImageURL"];
// var content = PermutationObj[j]["ElectronicPopContent"];
// break
// }
var content = PermutationObj[i]["ElectronicPopContent"];
marker = new google.maps.Marker({
position: LatLngPair,
map: map,
draggable: false,
// icon: image,
shape: shape,
anchorPoint: new google.maps.Point(12, -25)
});
//Setting up the content of the info window dynamic wise.
var infowindow = new google.maps.InfoWindow({
content: content
});
//Setting up an event listener, When the user clicks the marker, an info window opens.
google.maps.event.addListener(marker, 'click', function () {
infowindow.setContent(content);
infowindow.open(map, marker);
});
}
}
Changed a few things, the first is having only one instance of the InfoWindow, the other is storing the content as a marker property and use it on the click, the last is having an instance per marker by using var marker = ... instead of marker = ... Let me know if this works for you.
var locationObj;
var PermutationObj;
var map;
var mapOptions;
var infowindow = new google.maps.InfoWindow({ });
var shape = {
coord: [1, 1, 1, 20, 18, 20, 18, 1],
type: 'poly'
};
function setMap(locationList, permutation) {
// List of Lat,Lng
locationObj = $.parseJSON(locationList);
PermutationObj = $.parseJSON(permutation);
var qMapTypeId = google.maps.MapTypeId.SATELLITE
var LatLngCenter = new google.maps.LatLng(34.163291, -118.685123);
var mapOptions = {
zoom: 4,
center: LatLngCenter,
mapTypeControl: true,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
}
}
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
var bounds = new google.maps.LatLngBounds();
for (i in locationObj) {
var LatLngPair = new google.maps.LatLng(locationObj[i]["Lat"], locationObj[i]["Lng"]);
//Are you sure you need these 2 lines here?
bounds.extend(LatLngPair);
map.fitBounds(bounds);
var marker = new google.maps.Marker({
position: LatLngPair,
map: map,
draggable: false,
shape: shape,
anchorPoint: new google.maps.Point(12, -25),
infoWindowContent: PermutationObj[i]["ElectronicPopContent"]
});
//Setting up an event listener, When the user clicks the marker, an info window opens.
google.maps.event.addListener(marker, 'click', function () {
infowindow.setContent(marker.infoWindowContent);
infowindow.open(map, marker);
});
}
}

How to define custom size on Google Map when using closures in event listeners

I' am using Google Map to plot the marker and a small popup box that will appear when someone clicks on the market. Image is attached. By Default, Google has set fixed width of the Popup and I wanted to change its size. I was not able to anything on Documentation.
Below are my codes
<script type="text/javascript">
function initialize() {
var mapOptions = {
zoom: 5,
center: new google.maps.LatLng(-14.306407, -170.695018),
mapTypeId: google.maps.MapTypeId.TERRAIN
};
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
var voyagePlanCoordinates = [
new google.maps.LatLng(),
];
var voyagePath<?php echo $voyage_id; ?> = new google.maps.Polyline({
path: voyagePlanCoordinates,
geodesic: true,
strokeColor: "",
strokeOpacity: 1.0,
strokeWeight: 5
});
voyagePath.setMap(map);
setMarkers(map, voyages);
}
var voyages = [];
function setMarkers(map, locations) {
var image = {
url: '/wp-content/themes/theme/resources/images/marker.png',
size: new google.maps.Size(20, 32),
origin: new google.maps.Point(0,0),
anchor: new google.maps.Point(0, 32)
};
for (var i = 0; i < locations.length; i++) {
var voyage = locations[i];
var myLatLng = new google.maps.LatLng(voyage[1], voyage[2]);
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
icon: image,
title: voyage[0],
zIndex: voyage[3]
});
voyage_msg(marker, i);
}
}
function voyage_msg(marker, num){
var message = [];
var infowindow = new google.maps.InfoWindow({
content: message[num]
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(marker.get('map'), marker);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
Please Help!
You don't need any extra code or api call to set the width of the popover. All you need is basic CSS
.map-closures{
width: 200px;
}
That should do the trick.

open multiple infowindow from external click javascript

Hi i am using google map to show my search locations, below the map it lists the search result. wen the user clicks the below result the google map show the infowindow .
function setMarkers(map, locations)
{
var infoWindow = new google.maps.InfoWindow({});
var markers = new Array();
var image = new google.maps.MarkerImage('images/pin_red.png',
new google.maps.Size(32,39),
new google.maps.Point(0,0),
new google.maps.Point(18, 30));
var shape = {
coord: [1, 1, 1, 20, 18, 20, 18 , 1],
type: 'poly'
};
var alph = 65;
for (var i = 0; i < locations.length; i++) {
var beach = locations[i];
var myLatLng = new google.maps.LatLng(beach[1], beach[2]);
var title = beach[0].split('~~');
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
icon: 'http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld='+String.fromCharCode(alph)+'|FF0000|000000',
shape: shape,
title: title[0]+'<br>'+title[1],
zIndex: beach[3]
});
$('#mappoint-'+String.fromCharCode(alph)).bind('click', function() {
google.maps.event.trigger(marker, 'mouseover')
});
google.maps.event.addListener(marker, 'mouseover', function() {
infoWindow.setContent(this.title);
infoWindow.open(map, this);
});
alph = parseInt(alph)+1;
}
}
This is the function i am using, it show the last created infowindow while clicking any result, anyone have any idea ?
$('#mappoint-'+String.fromCharCode(alph)).bind('click', function() {
google.maps.event.trigger(marker, 'mouseover')
});
This section having the problem, this binds only for last created marker .

Categories

Resources