jQuery/Javascript: Google Maps: How to toggle multiple pins on a map? - javascript

I have a database of locations which I want to be able to print on a map. Ideally there should be one map with multiple pins for each location you have toggled on. So click a button for location X and it shows up on the map. Click the button for location Y and it shows up on the same map. Click X again and it hides from the map.
Currently I have it so I click on X and the map gets redrawn centered around point X.
Here is the HTML for each button:
<input type='button' data-lat='38.89864400' data-long='-77.05283400'
data-when='20 Aug at 2:00am' value='Location X' class='click' />
The jQuery I'm using is:
jQuery(document).ready(
function initialize() {
jQuery("input.click").click(function() {
showOnMap(jQuery(this).data('lat'), jQuery(this).data('long'), jQuery(this).data('when'));
});
}
);
function showOnMap(lat, long, message) {
var myLatlng = new google.maps.LatLng(lat, long);
var mapOptions = {
zoom: 13,
center: myLatlng
}
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: message
});
google.maps.event.addDomListener(window, 'load', showOnMap);
}
Is there an easy way to switch from what I have to what I want? I've searched for a while but no one seems to be asking this use case in a browser, just Android (which I'm not doing).
Thanks!

There is an example in the documentation on how to hide/show markers. In short, a marker is:
hidden by setting its map to null
showed by setting its map to map
To do so, you will need to access each marker individually. If you have a definite number of locations, it can be done by naming them with different names (eg var markerLocationX, var markerLocationY, etc). Otherwise, the markers need to be stored in an array.
Supposing you have a definite number of known locations to toggle the markers, your javascript code may look like this:
function toggleMarker(markerName) {
if (markerName.getMap() == null) {
markerName.setMap(map);
} else {
markerName.setMap(null);
}
}

Related

Google maps API. Adding Markers

I have updated my code so now the Map remains in tact when I add the script to place the markers. Unfortunately, The add markers instruction isn't working. The data containing the coordinates is pulled from SQL and converted to JSON using C# and stored as a Hidden Field. This in itself works as it should but I can't seem to get my Script to read the data and pass the info to the map and drop the marker. Here is my code as it stands right now.
<body>
<form id="form1" runat="server">
<asp:HiddenField runat="server" ID="locationData" /> H<%--IDDEN FIELD CONTAINING DATA--%>
</form>
<div class="header">
</div>
<div id="map"></div>
<script type="text/javascript">
function initMap() {
var options = { //MAP LOAD OPTIONS
zoom: 5.8,
center: { lat: 54.251186, lng: -4.463196 }
}
var map = new
google.maps.Map(document.getElementById('map'), options); //LOOADS MAP
// Add Markers
var markers;
var arr = document.getElementById("LocationData"); //CALLS HIDDEN FIELD AND SETS RULES FOR ADDING MARKERS TO THE MAP
if (arr == "") {
markers = {};
}
else {
markers = $.parseJSON(arr.Latitude, arr.Longitude);
};
for (i = 0; i < markers.length; i++) { //LOOPS THROUGH THE DATA AND ADDS MARKER AS PER LAT AND LONG
var data = markers[0];
var myLatlng = new google.maps.LatLng(data.Latitude, data.Longitude);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: data.building
});
}
}
</script>
Mike
I am assuming you are viewing the above html response from asp on a web browser (Google Chrome), so I can help you debug the issue. On the Google chrome at the top right corner click on the '3 dots' (menu) then click on 'More Tools' then click on 'Developer Tools', which would by default open the 'Console' tab window and you can find the error(s) from your html code in 'red' color text. Try to analyze the error and also you can add more çonsole.log() or console.log('') in your JavaScript code, which can provide you more information and help you resolve the issue.

Preserving Google map zoom to kml layer on checkbox click

I'm attempting to add multiple kml layers to a map that can be turned on and off with check boxes. I got that part working (yay!). When I click on a layer to turn it on, it zooms in (this is fine), but when I unclick to turn the layer off, it zooms back out to my map extent. How do I get it to preserve the zoom of the last loaded layer? Code below.
<script>
var map;
var watershedLayer = new google.maps.KmlLayer ({
url: 'http://mvihes.bc.ca/mapping/watersheds.kmz'
});
var ere1949Layer = new google.maps.KmlLayer ({
url: 'http://mvihes.bc.ca/mapping/ere1949.kmz'
});
function initialize() {
var parksville= new google.maps.LatLng(49.316786, -124.308768);
var mapOptions = {
zoom: 9,
center: parksville
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
check();
}
function check()
{
if(document.getElementById('watersheds').checked)
{watershedLayer.setMap(map);}
else
{watershedLayer.setMap(null);}
if(document.getElementById('ere1949').checked)
{ere1949Layer.setMap(map);}
else
{ere1949Layer.setMap(null);}
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
I tried using the preserveViewport function but it just stopped the layer from zooming in, which is not what I wanted. I'm new to javaScript so possibly I'm missing something obvious...any help would be appreciated!
jsfiddle
Set the map-property of a selected layer only when it's not set yet:
function check()
{
if(document.getElementById('watersheds').checked)
{if(!watershedLayer.getMap())watershedLayer.setMap(map);}
else
{watershedLayer.setMap(null);}
if(document.getElementById('ere1949').checked)
{if(!ere1949Layer.getMap())ere1949Layer.setMap(map);}
else
{ere1949Layer.setMap(null);}
}
http://jsfiddle.net/jhagmq7L/16/
You can also attach max and min zoom levels to the map, something to consider the over all map zoom when loading kml layers.
// sets the min and max zoom levels of the map
var opt = { minZoom: 6, maxZoom: 18 };
map.setOptions(opt);

Google Map with Sidebar that Zooms to a Specific Location

I'm working on a javascript Google map where I have marked the location of each of the state capitals with a custom marker and a title of that capital and state. Right now when you view the map you see the whole US with each marker. I want to keep that but add a sidebar where you click the name of a state and the map zooms to the state and capital. I would also like to add a link that zooms out view the full map. Does anyone have a tutorial on how to do this? I found several examples of Google maps with sidebars but none that zooms to a specific location.
Edit:
This is what I am trying to achieve: http://econym.org.uk/gmap/example_map2.htm
Here is the code I am working with:
<script>
function init() {
var myOptions = {
zoom: 4,
center: new google.maps.LatLng(38.781494, -96.064453),
mapTypeId: google.maps.MapTypeId.ROAD
};
var map = new google.maps.Map(document.getElementById("map"), myOptions);
var image = 'Alabama.png';
var myLatLng = new google.maps.LatLng(32.366805, -86.299969);
var AlabamaMarker = new google.maps.Marker({
position: myLatLng,
map: map,
icon: image,
title:"Montgomery, Alabana"
});
}
google.maps.event.addDomListener(window, 'load', init);
</script>
You need to associate listeners (for example, using jquery) with the click event on your state names. Provided they had an id attribute with the USPS code, it would be something like
jQuery(document).on('click','#RESET',function() {
map.setZoom(5);
map.setCenter({lat:41, lng:-89.5});
});
jQuery(document).on('click','#CA',function() {
map.setZoom(7);
map.setCenter({lat:36.4, lng:-120.9});
});
jQuery(document).on('click','#FA',function() {
map.setZoom(7);
map.setCenter({lat:28, lng:-81});
});
You see, I included one link with id RESET that allows me to reset to the initial state.
Here you can see it at work
http://bl.ocks.org/amenadiel/38e0541592bf331cb298

How to add multiple markers for single location on Google Map

I'm using Google Maps version 3 and would like to add two markers for a single location on the map.
One would be the default marker which appears with Google Maps, but second would show the name of the brand associated with that location.
My code is
function initialize() {
var filterLatlng = new google.maps.LatLng(18.928184,72.832601);
var mapOptions = {
center: filterLatlng,
zoom: 19,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var marker = new google.maps.Marker({
position: filterLatlng,
title:"Filter Shop"
});
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
marker.setMap(map);
}
You probably want this library:
http://code.google.com/p/google-maps-utility-library-v3/source/browse/trunk/maplabel/src/maplabel.js?r=303
It will allow you to add a label on the map.
That label will be attached to a hidden marker like you described.
The use is quite simple you should be able to figure it out quite easy.

How to get some information in google maps without click event on marker and show this in a div, other than infoWindow

Hi I am showing some markers on my google map and on click of the marker, I am calling the click event and showing some info about that place to the right side(area other than Map and not as an infoWindow). Now this event gets fired on click, and by default when page loads my div remains blank, How can I have the div the basic information being shown up once the map loads up. I need to show the information that corresponds to the marker that is the center point of the map, and later when the users click the marker icons the info should change and correspond to the particular marker being clicked
I have tried something but it doesn't work:
function loadMap() {
var myLatlng = new google.maps.LatLng(40.46998, -3.68705);
var myOptions = {
zoom: 3,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map"), myOptions);
var places = [];
places.push(new google.maps.LatLng(51.43581, -0.51744));
places.push(new google.maps.LatLng(48.87187, 2.31764));
places.push(new google.maps.LatLng(45.45979, 9.19681));
var infowindow;
for(var i = 0; i<places.length; i++) {
var marker= new google.maps.Marker({
position: places[i],
map: map,
title: 'Place' + i
});
(function (i,marker){
google.maps.event.addListener(marker, 'click' , function() {
infowindow.setContent('PLace Number' + i)
infowindow.open(i, marker)
});
});(i, marker);
}
}
$("document").ready(function () {
loadMap();
});
UPDATE EDITED
Basically I need something like Layer KML features
But the info should come on the right hand side by default for the first time. Later on when the marker is clicked, the info should change. I am also not adamant that I need this info in a kml file(xml is fine with me as well). I can just have a marker and info should popup on click and for the first time be default as well depending on the location of the user.
Bottom Line: I need the info to appear on click of a marker and by default when the page loads the info should appear corresponding to the center point of the map. which means users coming from different locations will see different info's corresponding to their location from where they are coming.(I am centering the map based on users location)
You can use the addDomListener event of the google maps api. Something like this:
<script>
function initialize() {
// Map initialization
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
<body>
<div id="map_canvas"></div>
</body>
Although the above code is Maps Javascript API code, the addDomListener() method binds to the window object of the browser and allows the API to communicate with objects outside of the API's normal domain.
further reading
Actually the basic Idea is that you need to read an XMl and parse the data and and show this in a seperate div on right side., This div you can create dynamically when you load the map e-g:
$("#body").append("<div class='newdiv'></div>")
From the google Docs in the section about InfoWindow:
Note that if you call open() without passing a marker, the InfoWindow
will use the position specified upon construction through the
InfoWindow options object.
So in your code, why don't you simply init your infoWindow and call the open() method? I am not particularly familiar with the api, but how about:
var infowindow = new google.maps.InfoWindow({
content: 'your initial text'
});
infowindow.open();
Or if you need the marker for special purposes on the infowindow, init an marker with the center position and use that in the infowindow.open(your_initial_pos) call.
You can use jQuery to .triger() a click event on the first marker on document.ready:
$(marker).trigger('click');
This will run the code you have already written and make it so when the page loads your div will be populated with data from whatever element you trigger the click on.
When you bind to document.ready you don't need encapsulate document in quotes:
$(document).ready(function () {...});
Or you could use the short-hand if you're into that sort of thing:
$(function () {...});
UPDATE
You can place the trigger function call after your for loop where you are setting up the markers:
for(var i = 0; i<places.length; i++) {
var marker= new google.maps.Marker({
position: places[i],
map: map,
title: 'Place' + i
});
(function (i,marker){
google.maps.event.addListener(marker, 'click' , function() {
infowindow.setContent('PLace Number' + i)
infowindow.open(i, marker)
});
});(i, marker);
//only run on the first marker
if (i === 0) {
//trigger a click event to show the first info-window
$(marker).trigger('click');
}
}
You can fire a tilesloaded event on the map object. Check out the Map reference for events
tilesloaded waits until the map tiles are actually loaded before firing. Using your code, you could do something like this:
function loadMap() {
var myLatlng = new google.maps.LatLng(40.46998, -3.68705);
var myOptions = {
zoom: 3,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map"), myOptions);
google.maps.event.addListener(map, 'tilesloaded', function() {
doSomething();
});

Categories