Hide Markers on Click with Google Maps API - javascript

I am building a search form using Google Maps Javascript V3 API. I would like to add some filters that will hide certain types of markers on the map when clicked. The markers to hide are represented with
locations[i][11] == 'Other'
HTML:
Hide Other Markers
JavaScript:
var geocoder;
function initialize() {
geocoder = new google.maps.Geocoder();
var mapOptions = {
center: { lat: 48.509532, lng: -122.643852}
};
var map = new google.maps.Map(document.getElementById('map-canvas'),mapOptions);
var locations = <?php echo json_encode($locations_array); ?>;
var infowindow = new google.maps.InfoWindow();
var marker, i;
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
animation: google.maps.Animation.DROP,
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
var content = '';
infowindow.setContent(content);
infowindow.open(map, marker);
}
})(marker, i));
google.maps.event.addDomListener(document.getElementsByClassName('hideOtherMarkers')[0], 'click', function() {
if (locations[i][11] == 'Other') {
marker.setVisible(false); // maps API hide call
}
});
}
}
google.maps.event.addDomListener(window, 'load', initialize);
When I click the link nothing fires, verified with alerts. I also tried google.maps.event.addListener (without Dom) with no success.

As commented by geocodezip this approach will not work, because i will always point behind the end of locations. Additionally this would hide at best 1 marker (the last marker that has been created).
Possible approach:
Store the visible-state of the markers in a MVCObject:
map-options:
var mapOptions = {
center: { lat: 48.509532, lng: -122.643852}
//that's the property where we store the state
visibility:new google.maps.MVCObject
};
inside the loop, after the creation of marker:
//when the state is not set yet, set it
if(typeof map.get('visibility').get(locations[i][11])==='undefined'){
map.get('visibility').set(locations[i][11],true);
}
//bind the visible-property of the marker to the state
marker.bindTo('visible',map.get('visibility'),locations[i][11]);
add the listener(outside of the loop):
google.maps.event.addDomListener(
document.getElementsByClassName('hideOtherMarkers')[0],
'click',
function() {
//simply set the desired property of the MVCObject to false
map.get('visibility').set('Other',false);
});
Demo: http://jsfiddle.net/doktormolle/5L2392mL/

Related

Google maps API recenter my map

My code for the initialization of the API looks like so:
jQuery(function($) {
// Asynchronously Load the map API
var script = document.createElement('script');
script.src = "http://maps.googleapis.com/maps/api/js?sensor=false&callback=initialize";
document.body.appendChild(script);
});
function initialize() {
var bounds = new google.maps.LatLngBounds();
var mapOptions = {
mapTypeId: 'roadmap'
};
// Display a map on the page
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
map.setTilt(45);
// Multiple Markers
var markers = [
//php code to get markers from DB
];
// Info Window Content
var infoWindowContent = ['some text here'];
// Display multiple markers on a map
var infoWindow = new google.maps.InfoWindow(), marker, i;
// 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]
});
//push markers to mapMarkers array.
mapMarkers.push(marker);
// 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));
// Automatically center the map fitting all markers on the screen
map.fitBounds(bounds);
}
}
Problem is I dont want the map to be centered around my markers I get from the database anymore. But if I delete map.fitBounds(bounds); and try to use map.setCenter({lat: -34, lng: 151}); I get a blank screen. If I even touch anything in this code I get a blank screen instead of my map!
A map must have a zoom.
You didn't initially set a zoom for the map.
When you use fitBounds() the zoom will be set automatically, but when you didn't use it the zoom is still missing.
Solution: set a zoom in mapOptions

how to open popup on click of a marker from the directions service?

UPDATE
when i click green marker,it's display address of location.can i change it?
LATER EDIT :
is it possible to open popup on click of a marker from the directions service?
or try the other way like only hide a marker from the directions service(green marker) and display only red marker(hide only green marker not it's route)?is it good way?
if not possible, please suggest some alternative ideas.
OLDER:
i have a two types of marker on google map.the red marker is normal marker which represent location.and green marker is route marker(its represent many of waypoints of the map).
I modify the infowindow with textbox.which is open on click red marker.
actually i am trying to do is, first i place multiple markers on google map then i draw route between this markers.this thing is done.reminder thing is on click green marker one popup is opened in which user enter price and then click the button.then i got this value and store it to database.
the problem is:
(1) how to open same infowindow on click of green marker?
in short,how to write a code for display infowindow on click of of green marker.
how to find click event of green marker?
code is:
<script type="text/javascript">
var markerarray=new Array();
//for way points
var waypts=[];
//array in json format for placing multiple marker
var locations = <?php echo json_encode($lat1);?>;
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 11,
center: new google.maps.LatLng(23.0171240, 72.5330533),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow();
<!-- ************* for placing markers ************ -->
var marker, i;
for (i = 0; i < locations.length; i++)
{
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][3], locations[i][4]),
map: map //enable if you want marker
});
//push value into way points
waypts.push({
location:locations[i][0],
stopover:true
});
//create array for polyline
markerarray[i] = marker.getPosition();//(Array(locations[i][5], locations[i][6]));
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
var data='<div style="height:150px !important"><table><tr><td>Enter Price</td></tr><tr><td><input type="text" name="prc" id="prc" /></td></tr></table></div>';
infowindow.setContent(data);
infowindow.open(map, marker);
}
})(marker, i));
}
<!-- ************** for route between markers ******************* -->
var first=locations[locations.length-1][0];
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
//directionsDisplay = new google.maps.DirectionsRenderer();
directionsDisplay = new google.maps.DirectionsRenderer({
polylineOptions: {
strokeColor: 'red',//"black",
strokeOpacity: 1.0,
strokeWeight: 3
}
});
var start = locations[0][0];//"Bopal, Ahmedabad, Gujarat, India";
var end = locations[locations.length-1][0];//"Nikol, Ahmedabad, Gujarat, India";
//remove start destination from array
waypts.shift();
//remove end destination from array
waypts.pop();
var request = {
origin:start,
destination:end,
waypoints:waypts,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
directionsDisplay.setMap(map);
</script>
Thanks in advance.
It is not impossible but it will take some time for code, The way is if you are using for mobile device then you need to accelerator from your device and call geolocation function on position change I think you understand and the second method is from purely javascript method for that you need to call your geolocation function within set Interval understand also draw line separately from marker your marker function only calls within set Intervals for getting your current location with infowindow. Example is :
var map;
function initialize() {
var mapOptions = {
zoom: 6,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
//keep this in setInterval
// Try HTML5 geolocation
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
var infowindow = new google.maps.InfoWindow({
map: map,
position: pos,
content: 'Location found using HTML5.'
});
map.setCenter(pos);
}, function() {
handleNoGeolocation(true);
});
} else {
// Browser doesn't support Geolocation
handleNoGeolocation(false);
}
}
function handleNoGeolocation(errorFlag) {
if (errorFlag) {
var content = 'Error: The Geolocation service failed.';
} else {
var content = 'Error: Your browser doesn\'t support geolocation.';
}
var options = {
map: map,
position: new google.maps.LatLng(60, 105),
content: content
};
var infowindow = new google.maps.InfoWindow(options);
map.setCenter(options.position);
}
//close here your set interval
google.maps.event.addDomListener(window, 'load', initialize);
It's possible. You can hide the default marker such that you can build a custom marker on the clicked location. This code is to hide the marker.
var rendererOptions = {
suppressMarkers : true
}
var directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);

Google Maps overlay wont position over correct markers

I'm trying to make a list of markers to pin onto a map, each having its own overlay. It's mostly working, however the overlays are all being positioned over the top of one another instead of its corresponding marker.
Code is as follows:
var myCenter = getMyLocation();
function initialize()
{
var mapProp = {
center: myCenter,
zoom:9,
mapTypeId:google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("googleMap"),mapProp);
var locations = [
{lat: -27.646670, lng: 152.86918630, text: 'Address #1'},
{lat: -27.6446550, lng: 152.7822390, text: 'Address #2'},
{lat: -27.6062480, lng: 152.7889550, text: 'Address #3'}
];
// Loop through our list and plot them on the map
locations.forEach(function (l) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(l.lat, l.lng),
});
marker.setMap(map);
// Create our infoWindow panel for our marker
var infoWindow = new google.maps.InfoWindow({
content: l.text
});
// Bind click event for our marker
google.maps.event.addListener(marker, 'click', function () {
infoWindow.open(map, marker);
});
});
}
google.maps.event.addDomListener(window, 'load', initialize);
I have a feeling that the issue is something to do with the on click addListener event
You're simply missing a var:
marker = new google.maps.Marker(...
should be:
var marker = new google.maps.Marker(
As a result, you only have a single global marker variable instead of a unique one for each marker as you should.
Since you're using .forEach with a callback function, that callback function provides you with a closure for each iteration of the loop. So all you need is to take advantage of that closure by making marker a local variable inside the callback.
Maybe closure will help you? Marker is an object, because of it on every loop link to it changes. Closure will prevent it.
google.maps.event.addListener(marker, 'click', (function(marker){ return function () {
infoWindow.open(map, marker);
};})(marker));

Markers won't show on google maps

I need to place multiple markers on a google map. Here's the problem: I have an array of latitude/longitude data. I need to make a marker appear on the map for each lat/lng pair. But it won't. If I ask the function to print out the coordinates instead of marking them on the, map, it works fine. I don't get an error message either way, so I'm stuck. The page displays the map but without any markers. Here's the code of the function that should add markers:
//adds markers to the map
function addMarkers(locarray) {
var infowindow = new google.maps.InfoWindow();
var marker, i;
for (i = 0; i < locarray.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locarray[i][0], locarray[i][1]),
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent('some words');
infowindow.open(map, marker);
}
})(marker, i));
}
}
Here's the initialize function (called on body load):
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = codeAddress("<?php echo $_POST['postal']; ?>");
var myOptions = {
zoom: 11,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
}
geocoder and map are declared as global variables. The codeAddress function returns lat and lng of the place I want to center the map around, it's been tested and works perfectly. It is NOT the problem, I'm leaving it out to simplify and keep PHP out of this.
And here is the script that declares the array and calls the addMarkers function:
<script type='text/javascript'>
var locations = [
[-33.890542, 151.274856],
[-33.923036, 151.259052],
[-34.028249, 151.157507]
];
addMarkers(locations)
</script>
Does anyone see anything wrong with this?

How do I close an infowindow with Google Maps 3 API?

I've seen the other posts, but they dont have the markers being looped through dynamically like mine. How do I create an event that will close the infowindow when another marker is clicked on using the following code?
$(function(){
var latlng = new google.maps.LatLng(45.522015,-122.683811);
var settings = {
zoom: 10,
center: latlng,
disableDefaultUI:false,
mapTypeId: google.maps.MapTypeId.SATELLITE
};
var map = new google.maps.Map(document.getElementById("map_canvas"), settings);
$.getJSON('api',function(json){
for (var property in json) {
if (json.hasOwnProperty(property)) {
var json_data = json[property];
var the_marker = new google.maps.Marker({
title:json_data.item.headline,
map:map,
clickable:true,
position:new google.maps.LatLng(
parseFloat(json_data.item.geoarray[0].latitude),
parseFloat(json_data.item.geoarray[0].longitude)
)
});
function buildHandler(map, marker, content) {
return function() {
var infowindow = new google.maps.InfoWindow({
content: '<div class="marker"><h1>'+content.headline+'</h1><p>'+content.full_content+'</p></div>'
});
infowindow.open(map, marker);
};
}
new google.maps.event.addListener(the_marker, 'click',buildHandler(map, the_marker, {'headline':json_data.item.headline,'full_content':json_data.item.full_content}));
}
}
});
});
I finally figured it out... no thanks to anyone here... It was actually fairly easy:
First, set up some vars to store the infowindow:
var infowindow;
Then add this to wherever your onClick function is that triggers the other infowindow.open(). Put it above the open though:
if(infowindow) {infowindow.close()}
Inside your loop or however else you are adding markers.
E.g. in full action:
At the very top of my script:
var infowindow;
Inside my loop of adding markers:
function buildHandler(map, marker, content) {
return function() {
if(infowindow) {infowindow.close()}
infowindow = new google.maps.InfoWindow({
content: 'My Content here'
});
infowindow.open(map, marker);
};
}

Categories