Multiple google map on modal view Ruby on Rails - javascript

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

Related

How to create a moving marker in google maps

I a using Google Maps in my app.
The user is to be able to place a marker on any place in the map.
To this end I wrote the following code:
var marker;
function myMap() {
var mapCanvas = document.getElementById("map-canvas");
var myCenter=new google.maps.LatLng(50.833,-12.9167);
var mapOptions = {center: myCenter, zoom: 5};
var map = new google.maps.Map(mapCanvas, mapOptions);
google.maps.event.addListener(map, 'click', function(event) {
//marker.setMap(null); // this line does not work
placeMarker(map, event.latLng);
});
}
function placeMarker(map, location) {
marker = new google.maps.Marker({
position: location,
map: map
});
}
The marker is supposed to always move to the place where the user clicked.
The line
marker.setMap(null);
is supposed to remove the old marker (before the new marker is placed).
However, with this line in the code I cannot place any markers any more. Not including this line means that every marker stays in the map and is not removed (i.e. the map is filling up with markers over time).
Look at the javascript console, you will see Uncaught TypeError: Cannot read property 'setMap' of undefined. The first time, marker is null, you need to only set its map property to null if it already exists.
google.maps.event.addListener(map, 'click', function(event) {
if (marker) marker.setMap(null);
placeMarker(map, event.latLng);
});
proof of concept fiddle
code snippet:
var marker;
function myMap() {
var mapCanvas = document.getElementById("map-canvas");
var myCenter = new google.maps.LatLng(50.833, -12.9167);
var mapOptions = {
center: myCenter,
zoom: 5
};
var map = new google.maps.Map(mapCanvas, mapOptions);
google.maps.event.addListener(map, 'click', function(event) {
if (marker) marker.setMap(null);
placeMarker(map, event.latLng);
});
}
function placeMarker(map, location) {
marker = new google.maps.Marker({
position: location,
map: map
});
}
google.maps.event.addDomListener(window, "load", myMap);
html,
body,
#map-canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map-canvas"></div>
The problem is that you try to use method setMap after the first click when marker variable doesn't have this method. So, first check if marker has the method and then call it.
google.maps.event.addListener(map, 'click', function(event) {
// check if setMap is available and call it.
if(marker.hasOwnProperty('setMap')){
marker.setMap(null);
}
placeMarker(map, event.latLng);
});

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;
});

Set marker on Google Map when changing a checkbox

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.

How to show a map focused on a marker using a click event on Google Maps JavaScript API v3?

I created a map that focuses on a user's location. The map has a single marker with an info window. When a user clicks on the info window it gives him a hyperlink to an info page (info.html). I want to create an option that will allow the user to go back from the info page to the map, and the map should be focused on the same marker (not on his current location). It's basically going the opposite way. It sounds pretty simple, but I have no idea how to code this.
I guess I can build a different map for every marker, but that seems highly unlikely to be the right solution. Any help would be appreciated.
This is my attempt with the script, (initialize2() doesn't work):
$(document).ready(function() {
getLocation();
});
var map;
var jones = new google.maps.LatLng(40.59622788325198, -73.50334167480469);
function getLocation() {
navigator.geolocation.getCurrentPosition(
function(position) {
var myLatLng = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
map.setCenter(myLatLng);
},
function() {
alert("Please enable location detection on your device");
}
);
}
function initialize() {
var mapOptions = {
center: map,
zoom: 9,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
var infowindow = new google.maps.InfoWindow({
});
var marker1 = new google.maps.Marker({
position: jones,
map: map
});
google.maps.event.addListener(marker1, 'click', function() {
infowindow.setContent('<h4>Jones Beach</h4>See info');
infowindow.open(map,marker1);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
// this is my attempt to focus on the marker
// there will be a button that will evoke this function from info.html
function initialize2() {
var mapOptions2 = {
zoom: 14,
center: new google.maps.LatLng(40.59622788325198, -73.50334167480469),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions2);
}
google.maps.event.addDomListener(window, 'load', initialize2);
What about using a hash in the url?
Try using "http://students.example.com/test.html#one":
$(function() {
var places = {
one: [40.59622788325198, -73.50334167480469],
two: [50.59622788325198, -71.50334167480469]
};
var div = $('#map-canvas');
var map = new google.maps.Map(div.get(0), {
center: map,
zoom: 9,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var markers = {};
$.each(places, function(name) {
markers[name] = new google.maps.Marker({
position: new google.maps.LatLng(this[0], this[1]),
map: map
});
});
var place = location.hash.substr(1);
if(place in places) {
map.setCenter(markers[place].getPosition());
}
});

Google Maps don't fully load

I have a somewhat strange problem. I have two maps on my site, a big one and a small one. I want to use the big one to show a route to a certain address. I'm now trying to implement the two maps but get a weird problem. The small map is working fine, but on the big map only a small area of the div is filled with the map, the rest is empty. (See the image.)
I use the following code to display the two maps:
function initialize() {
var latlng = new google.maps.LatLng(51.92475, 4.38206);
var myOptions = {zoom: 10, center: latlng,mapTypeId: google.maps.MapTypeId.ROADMAP};
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var marker = new google.maps.Marker({position: latlng, map:map, title:"Home"});
var image = '/Core/Images/Icons/citysquare.png';
var myLatLng = new google.maps.LatLng(51.92308, 4.47058);
var cityCentre = new google.maps.Marker({position:myLatLng, map:map, icon:image, title:"Centre"});
marker.setMap(map);
var largeLatlng = new google.maps.LatLng(51.92475, 4.38206);
var largeOptions = {zoom: 10, center: largeLatlng,mapTypeId: google.maps.MapTypeId.ROADMAP};
var largeMap = new google.maps.Map(document.getElementById("largeMap"), largeOptions);
var largeMarker = new google.maps.Marker({position: largeLatlng, map:largeMap, title:"Cherrytrees"});
largeMarker.setMap(largeMap);
}
[..]
jQuery(document).ready(function () {
[..]
initialize();
});
What's going wrong here?
EDIT:
Unfortunately the suggestions below doesn't seem to work. The closes i came is to remove the display:none from the elements and set the elements to hide with jquery
[..]
jQuery(document).ready(function () {
[..]
$("#shadow").add($("#shadowContent"),$("#closebar"),$("#content")).hide();
});
With the following result
Yes, #Argiropoulos-Stavros but, Add it as a listener
google.maps.event.addListenerOnce(map, 'idle', function(){
google.maps.event.trigger(map, 'resize');
map.setCenter(location);
});
It will begin re-sizing after, map rendered.
I think you are using v3.
So google.maps.event.trigger(map, "resize");
Also take a look at here
I fixed it!
I made an own function for the largemap and placed it in the callback when the elements are opened
function largeMap(){
var largeLatlng = new google.maps.LatLng(51.92475, 4.38206);
var largeOptions = {zoom: 10, center: largeLatlng,mapTypeId: google.maps.MapTypeId.ROADMAP};
var largeMap = new google.maps.Map(document.getElementById("largeMap"), largeOptions);
var largeMarker = new google.maps.Marker({position: largeLatlng, map:largeMap, title:"Cherrytrees"});
largeMarker.setMap(largeMap);
}
[..]
$("#showRoute").click(function(e){
e.preventDefault();
$("#shadow").add($("#shadowContent"),$("#closebar"),$("#content")).fadeIn(500);
$("#shadowContent").show().css({'width':'750px','top':'25px','left':'50%','margin-left':'-400px'});
$("#closeBarLink").click(function(l){
l.preventDefault();
$("#shadow").add($("#shadowContent"),$("#closebar"),$("#content")).fadeOut(500);
});
largeMap();
});
Thanks anyway!!
call initialize(); function after you box active.
$(document).ready(function () {
$("#shadow").show(function () {
initialize();
})
});
When you're loading in the large map, try adding this at the end of your map code.
map.checkResize();
When Google Maps first renders on your page, it has the dimensions recorded so that it displays the map images in that size. If you're resizing the map dynamically, you need to tell the API to check the new size.
<script type='text/javascript' >
var geocoder, map;
function codeAddress() {
var address= '<?php echo $this->subject()->address; ?>';
geocoder = new google.maps.Geocoder();
geocoder.geocode({
'address': address
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var myOptions = {
zoom: 13,
center: results[0].geometry.location,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
icon:'http://rvillage.com/application/themes/rvillage/images/map-marker.png'
});
var infowindow = new google.maps.InfoWindow({ content: 'coming soon' });
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map, this);
});
}
});
}
jQuery(document).ready(function () {
codeAddress();
});
</script>
You are using pop up window with jQuery, and I guest you call initialize() function when document is ready ( $(document).ready(function() {initialize(); }) ).
Try call initialize() function after pop up windown showed.
Johnny

Categories

Resources