Set marker on Google Map when changing a checkbox - javascript

I need some help regarding the Google Maps API. I was able to initialize the map. Now I want to add some markers to it.
I have a set of checkboxes (they are called "networks"). Each checkbox has a hidden longitude and latitude field. If the checkbox is checked, a marker should be displayed on the map
I managed to do this with the detour, of clicking on the map. But I want to trigger the creation of new markers on change of the checkbox.
Here is how it works, when I click on the map the markers appear:
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 6,
center: {lat: 48.7791, lng: 9.0367}
});
google.maps.event.addListener(map, "click", function(event) {
//Get all checked Networks
var checked_network = $( ".checkbox-network:checked" );
checked_network.each(function(){
network_id = $( this ).data("network-id");
//Get the hidden location longitudes and latitudes for each checked network element
network_locations_latitude = $(".location_latitude_network_"+network_id).val();
network_locations_longitude = $(".location_longitude_network_"+network_id).val();
var marker = new google.maps.Marker({
position: new google.maps.LatLng(network_locations_latitude,network_locations_longitude),
map: map
});
});
});
}
Here is how I try to get it to work, with clicking on the checkboxes. Unfortunately nothing happens. The marker object shows up in the JavaScript console, but on the map no markers appear.
$(document).on('change','.checkbox-network', function() {
var checked_network = $( ".checkbox-network:checked" );
checked_network.each(function(){
network_id = $( this ).data("network-id");
//Get the hidden location longitudes and latitudes for each checked network element
network_locations_latitude = $(".location_latitude_network_"+network_id).val();
network_locations_longitude = $(".location_longitude_network_"+network_id).val();
console.log(network_id + " - " + network_locations_latitude);
var marker = new google.maps.Marker({
position: new google.maps.LatLng(network_locations_latitude,network_locations_longitude),
map: map,
title: "test"
});
console.log(marker);
});
});
What am I missing? How can I show the markers in the google-map with the onchangeevent of the checkboxes?

You have to initialize map variable globally. Currently scope of map variable only available inside initMap() function.
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 6,
center: {lat: 48.7791, lng: 9.0367}
});
$(document).on('change','.checkbox-network', function() {
var checked_network = $( ".checkbox-network:checked" );
checked_network.each(function(){
network_id = $( this ).data("network-id");
//Get the hidden location longitudes and latitudes for each checked network element
network_locations_latitude = $(".location_latitude_network_"+network_id).val();
network_locations_longitude = $(".location_longitude_network_"+network_id).val();
console.log(network_id + " - " + network_locations_latitude);
var marker = new google.maps.Marker({
position: new google.maps.LatLng(network_locations_latitude,network_locations_longitude),
map: map,
title: "test"
});
console.log(marker);
});
});

In the second snippet of your code, the map isn't defined because it's been defined in the scope of initMap(). I wonder why Google doesn't throw any errors.
change your initMap like below; move the map object to the global scope to be accessible from all scope (I always use this for my own projects)
initMap() {
window.map = new google.maps.Map(document.getElementById('map'), {
zoom: 6,
center: {lat: 48.7791, lng: 9.0367}
});
}
Here you should be more logical with the name map, so replace it with another name to avoid further conflicts.

Related

My custom marker on my google map wont show

I want to use an image(.jpg) that I have as a marker instead of the default marker/pin on my Google map. But the image won't show. There are lots of the same questions on this forum but none of them has helped me.
As soon as I take away the icon attribute from google.maps.Marker object the default marker shows. So that indicates that it somehow can't find my image... right?
Even when I hardcode the following link
https://maps.gstatic.com/mapfiles/place_api/icons/geocode-71.png
that marker image shows. But not the one I have locally in my project.
var map = null;
var mapHub;
var markers = [];
$(function ()
{
mapHub = $.connection.myHub;
//Start the hub
$.connection.hub.start(function ()
{
//Get the current location from the browser
navigator.geolocation.getCurrentPosition(function (position)
{
//Create the map element on the page.
map = new google.maps.Map(document.getElementById('map'), {
center: { lat: position.coords.latitude, lng: position.coords.longitude },
zoom: 15
});
//Add marker of current position to map
markers.push(new google.maps.Marker({
position: { lat: position.coords.latitude, lng: position.coords.longitude},
map: map,
icon: '~/Images/MapMarkerIcon.jpg'
}));
});
});
});

Multiple google map on modal view Ruby on Rails

I have a list of enterprices and need to display a map on their respective modal, for this I have this:
<div class="row" id="googleMap<%=enterprice.id%>" style="width 100%; height: 300px;" data1='<%=enterprice.latitud%>' data2='<%=enterprice.longitud%>'>
</div>
this code is on a html.erb file.
My function for loading the map:
<script>
function myMap(lat, long) {
var uluru = { lat: lat, lng: long};
var map = new google.maps.Map(document.getElementById('googleMap'), {
zoom: 4,
center: uluru
});
var marker = new google.maps.Marker({
position: uluru,
map: map
});
}
</script>
And a jquery helper for passing the data
$(document).on("ready", function() {
$('#googleMap<%=enterprice.id%>').each(function (index, element) {
var $this = $(element);
myMap($this.attr("data1"), $this.attr("data2"));
});
});
The problem is the map is only loading on the modal for the first cell, but not actually displaying any map.
And the other cells wont even load the map.
First of all, you don't need a map and a modal for each. You can have one and change them using JS. This way you will not overload your page with elements you will only use in series but never together in parallel.
You can have a map defined in your modal whenever the page is ready.
<script>
var map;
var old_marker;
function initMap() {
var point = {lat: 0, lng: 0};
map = new google.maps.Map(document.getElementById('map'), {
zoom: 12,
center: point,
mapTypeId: 'terrain'
});
// This event listener will call addMarker() when the map is clicked.
map.addListener('click', function(event) {
addMarker(event.latLng);
});
// Adds a marker at the center of the map.
addMarker(point);
}
// Adds a marker to the map and push to the array.
function addMarker(location) {
var marker = new google.maps.Marker({
position: location,
map: map
});
if(old_marker){
old_marker.setMap(null)
}
old_marker = marker
markers.push(marker);
map.setCenter(location);
}
</script>
Now we have to add a marker for each enterprise just by clicking on them.
I suggest adding a certain class to them
$(document).on("ready", function() {
initMap();
$(.enterprise).click(function(){
addMarker($this.attr("data1"), $this.attr("data2"));
});
});
By this, a marker will be added on the click on each enterprise and the map will focus that location. Now all you need to do is show the Modal.
References: https://developers.google.com/maps/documentation/javascript/examples/marker-remove

adding URL to map marker in Marker Cluster google map API

So basically what I am trying to do is have a map cluster and once you click into the clusters and click on the individule map markers you will be linked off to a different page on my website.
this is what i have so far. but i cant seem to pull the URLS through.. into different markers.
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: {lat: -39.3642, lng: 164.0444318}
});
// Add some markers to the map.
// Note: The code uses the JavaScript Array.prototype.map() method to
// create an array of markers based on a given "locations" array.
// The map() method here has nothing to do with the Google Maps API.
var markers = locations.map(function(location, i) {
return new google.maps.Marker({
position: location,
url: "http://travelpark.co.nz" //Will be different for each marker
});
});
// Add a marker clusterer to manage the markers.
var markerCluster = new MarkerClusterer(map, markers,
{imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m'});
}
var locations = [
{lat: -37.7862985, lng: 175.2773836},
{lat: -37.8011434, lng: 174.871265}
]
google.maps.event.addListener(markers, 'click', function() {
window.location.href = this.url;
});
The event listener at the bottom doesnt work.. i cant seem to figure this out. any help would be appreciated
Assign listener to each marker object not to the array. Use your map function itself to avoid 2 for loops:
var markers = locations.map(function(location, i) {
var marker = new google.maps.Marker({
position: location,
url: "http://travelpark.co.nz" //Will be different for each marker
});
google.maps.event.addListener(marker, 'click', function(){
window.location.href = this.url;
});
return marker;
});

How to add Markers on Google maps v3 API asynchronously?

I've been following the official documentation on how to add markers on the map so far
Nevertheless, I can see only one marker at a time max. If I try to add another one, then it doesn't work (I can't even see the first one).
My process is the following:
I initialize gmaps api:
jQuery(window).ready(function(){
//If we click on Find me Lakes
jQuery("#btnInit").click(initiate_geolocation);
});
function initiate_geolocation() {
if (navigator.geolocation)
{
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "https://maps.googleapis.com/maps/api/js?key=AIzaSyBbfJJVh0jL1X9b7XFDcPuV7nHD1HlfsKs&sensor=true&callback=initialize";
document.body.appendChild(script);
navigator.geolocation.getCurrentPosition(handle_geolocation_query, handle_errors);
}
else
{
yqlgeo.get('visitor', normalize_yql_response);
}
}
Then, I display it on the appropriate div. But when it comes to make the AJAX call, in order to get my locations of the different markers I'd like to display, It just doesn't work properly. Here is the code with a simple map displayed (since that's the only thing working for me so far).
function handle_geolocation_query(position){
var mapOptions = {
zoom: 14,
center: new google.maps.LatLng(position.coords.latitude, position.coords.longitude),
mapTypeId: google.maps.MapTypeId.SATELLITE
}
alert('Lat: ' + position.coords.latitude + ' ' +
'Lon: ' + position.coords.longitude);
$('#map-canvas').slideToggle('slow', function(){
var map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
});
$.when( getLakes(position.coords.latitude, position.coords.longitude)).done(function(results) {
// InitializeGoogleMaps(results);
if(results)
var data = results.map(function (lake) {
//Check if the lake has any open swims, if not, the button will not be clickable and an alert will pop up
if (lake.available>0)
clickable=true;
else
clickable=false;
return {
name: lake.name,
fishs: lake.fisheryType,
swims: lake.swims,
dist: lake.distance,
lat: lake.latitude,
long: lake.longitude,
id: lake.id,
avail: lake.available,
clickable: clickable,
route: Routing.generate('lake_display', { id: lake.id, lat: position.coords.latitude, lng: position.coords.longitude})
}
});
var template = Handlebars.compile( $('#template').html() );
$('#list').append( template(data) );
} );
};
So I'd like to add markers after the AJAX call. I've set up a function that I should call in the when()
function InitializeGoogleMaps(results) {
};
to display the markers in a foreach loop but nope, can't make it work. It looks like this :
CentralPark = new google.maps.LatLng(37.7699298, -122.4469157);
marker = new google.maps.Marker({
position: location,
map: map
});
Any help would be great !
Thanks
The main issue is that the map variable is declared only in the scope of the anonymous callback on slideToggle. First of all declare at the top-level function scope.
function handle_geolocation_query(position){
var map,
mapOptions = {
zoom: 14,
center: new google.maps.LatLng(position.coords.latitude, position.coords.longitude),
mapTypeId: google.maps.MapTypeId.SATELLITE
}
...
Then change the slideToggle callback to initialise the variable instead of redeclaring:
$('#map-canvas').slideToggle('slow', function(){
map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
});
Then you should pass map as a second parameter to your InitializeGoogleMaps function and call it using InitializeGoogleMaps(results, map). See where this gets you and hit me back with any questions.

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;

Categories

Resources