Load Google Map in new window by appending a button - javascript

I'm trying to append a button to a page that when clicked will display my google map in a new page. I have a button that when clicked either gives an error or gives a blank page.
My code:
$('.content--body__wrapper').append('<button id="show-map" />')
$('.content--body__wrapper').append(`<script>
document.getElementById("show-map").addEventListener("click", function(){
var center = {lat: -25.363, lng: 131.044};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: center
});
var marker = new google.maps.Marker({
position: center,
map: map,
});
})
</script>`);
$('.content--body__wrapper').append(`<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBcwtM8EBe7BE1NyPbU5SDYVYoBBtbtpTI&libraries=drawing" asyncdefer></script>`);
Error Code:
Edit: I took the callback out of the script source and I still don't get a page to load but I do have a lot less errors.

$('.content--body__wrapper').append('<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBcwtM8EBe7BE1NyPbU5SDYVYoBBtbtpTI&libraries=drawing&callback=initMap" async defer></script>');
In this line you say : when the API is loaded run the function called InitMap.
The problem is that this function is not definied in your js.
So remove this callback to use the documentReady event or remove documentReadyListener and create a function name initMap

Related

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

Why am I getting gray map after loading google map for second time by click event?

On my contact page, I have 3-4 addresses. I want to show one address on google map initially, on page load. And when the user clicks on different address then marker changes and moves to that address.
Initially, on page load, I am getting google map correctly. Map shows everything perfectly fine. But when I click on different addresses to move marker, marker moves but map gets gray colored. I mean the map is not showing perfectly as it shows for the first time.
Here is the screenshot for both
Screenshot 1 (Initially, Map loads perfectly fine)
Screenshot 2 (But When I click on address to change map location it shows gray colored map)
Here is my code
$(function(){
var map;
var marker;
// Load Map function
function loadMap(lat,long, fullAddress) {
var mapCanvas = document.getElementById("store-map");
let latLong = new google.maps.LatLng(lat, long);
var mapOptions = {
center: latLong,
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(mapCanvas, mapOptions);
marker = new google.maps.Marker({
position: latLong,
map: map,
animation: google.maps.Animation.DROP,
title: "Address"
});
var infoWindow = new google.maps.InfoWindow();
//Create and open InfoWindow.
infoWindow.setContent(fullAddress);
marker.addListener('click', function() {
infowindow.open(map, marker);
});
infoWindow.open(map, marker);
}
var defaultAddress = "448-451, Udyog Vihar, Phase - V</br>Gurugram, Haryana- 122001",
defaultLat = "28.4759576",
defaultLong = "77.0363467";
on page load load google map with default address
google.maps.event.addDomListener(window, 'load',
loadMap(defaultLat,defaultLong, defaultAddress));
// Get clickable item
var $locationItem = $('.store-location__item');
// On ckick of each address
$locationItem.on('click',function(event) {
// event.preventDefault();
/* Act on the event */
let lat = $(this).find('.lat').text();
let long = $(this).find('.lat').text();
let address = $(this).find('.store-location__address').html();
console.log(lat, long, address);
loadMap(lat,long,address);
});
});
Am I missing something? Why am I getting a gray colored map on click to change the location according to latitude and longitude after getting it from dom?
Note:
I have given latitude and longitude in HTML which has opacity 0 and
getting it on click to change the location
I also tried to create a new marker and remove the previous marker
instead of loading a new google map for performance but that is also
giving gray color issue.
I also tried to check css like 'overflow:visible' and
'overflow:hidden' but nothing happens regarding gray color issue.

Google maps API loads for a second then says check js console but no warnings or errors, any ideas

I'm using an API in a website for the first time, the google map pops up with the marker on my location that I have set but immediately goes gray and says check the console, in which there are no errors or warnings.
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap" async defer>
</script>
<script>
function initMap() {
var albany = {lat: 42.676762, lng: -73.821991};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: albany
});
var marker = new google.maps.Marker({
position: albany,
map: map
});
}
</script>
You need to include a valid key when you load the API.
The console should contain text to that effect and the URL that needs to be authorized.

Google maps js api. Many maps on page

I have accordion (twitter-bootstrap), and on each I have a map.
Accordion blocks generates in foreach. Maps generates as partial view, that takes model with latitude and longitude and block id.
It calls in foreach:
#if (item.Latitude != null)
{
<p>Map:</p>
<div class="map-margin">
#{Html.RenderAction("Map", "Default", new {model = item});}
</div>
}
And action returns this partial view:
#model MPS.Administration.Models.ReportModel
<div id="map-canvas-#Model.Id.ToString()" style="width: 470px; height: 270px;"></div>
<script type="text/javascript">
$('#map-canvas-#Model.Id').ready(function() {
initialize();
});
function initialize() {
var lat = #Model.Latitude;
var lng = #Model.Longitude;
var latlng = new google.maps.LatLng(#Model.Latitude, #Model.Longitude);
debugger;
var mapOptions = {
center: latlng,
zoom: 17,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var name = 'map-canvas-' + #Model.Id.ToString();
var map = new google.maps.Map(document.getElementById(name),mapOptions);
debugger;
// create a marker
var image = '../Content/Images/map_icon.png';
var marker = new google.maps.Marker({
position: latlng,
map: map,
icon: image
});
}
</script>
On layout I included script for js api.
Now I have 4 blocks, but only the last have map block (and it have only google logo and gray background without the map :( ). In debugger I see that lat and lng is same all 4 times. I think the problem is how I call initialize() map. Please help me to solve this issue.
The map si show only in the visible div. For the other you shuuld see only a grey background and in some case a small portion of the map in the upper left corner.
For see the map in every block you should use map.resize() or better use a genaration function for each time you show a new map. Initialize tipcally is call only when the windows is created and this this case the maps not visible fails

Google maps not loading within js tab

I am trying to make tabs using js to have more data on the site.
Please view: http://dev.ateo.dk/officelab-konferencecenter/
The two tabs at the top ("Billeder" and "kort") are made using js.
If i go into the tap called "kort", the google maps will not load completely - however if i right-click and choose "Inspect Element (Q)" using firefox, the map suddenly loads.
Also, the map is not centered. on the specific location - the location is in the top left corner.
You may notice a blank square below the tab div. This is the exact same code as used within the js tab. If i comment out the in js tab, the square which is blank, will work perfectly. So it somehow seems that the js tab combined with the js google maps are not working. Can this be the case, and if so, how is it fixed?
Below i am showing the code which will init the google maps and the taps on the page:
if($('body.single-konferencested').length > 0)
{
tabs();
}
if($('body.single-konferencested').length > 0)
{
$(document).ready(function() {
function initialize() {
var myLatlng = new google.maps.LatLng(place_lat,place_lng);
var mapOptions = {
zoom: 9,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById('gmap'), mapOptions);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
clickable : true
});
var pinIcon = new google.maps.MarkerImage(
"http://dev.ateo.dk/wp-content/themes/ateo/img/pin_marker.png",
null, /* size is determined at runtime */
null, /* origin is 0,0 */
null, /* anchor is bottom center of the scaled image */
new google.maps.Size(24, 40)
);
marker.setIcon(pinIcon);
var content_string = '<div id="gmap_info">'+
'<div id="siteNotice">'+
'</div>'+
'<h3 id="firstHeading" class="firstHeading">'+place_title+'</h3>'+
'<div id="bodyContent">'+
'<p>'+place_address+'<br />'+place_city_zip+'</div>'+
'</div>';
var infowindow = new google.maps.InfoWindow({
content: content_string
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map, marker);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
});
}
This following is the html showing the DOM for the "Kort" tab:
<div class="tabContent" id="kort" style="padding: 5px 10px;">
<h2>Kort</h2>
<div id="gmap" style="width: 600px; height: 400px;"></div>
<h2>test</h2>
</div>
Best regards
Patrick
If the div in which the map is going to live is not visible on page load the map will not load correctly. You should fire a resize once the div has come into view.
google.maps.event.trigger(map, 'resize');
You should bind this to the first click of the map tab.
It looks like the map is commented out of the second tab currently. If you could uncomment it it would be easier to help you more specifically!
EDIT:
to bind the function once, try this:
var tab = jQuery('ul#tabs li')[1]
jQuery(tab).one('click', function(){
google.maps.event.trigger(map, 'resize');
});
In order for the resize to work you will need access to the map variable from your init function.
It would also be easier to select the correct tab if you drop a class on it. That would be more reliable then getting the 2nd li in the tabs ul.
EDIT 2:
try adding the click function in your initialize code. Something similar to the following
var mapOptions = {
zoom: 9,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById('gmap'), mapOptions);
//add the code here, after the map variable has been instantiated
var tab = jQuery('ul#tabs li')[1]
jQuery(tab).one('click', function(){
google.maps.event.trigger(map, 'resize');
//fire a center event after the resize, this is also useful
// if bound to a window resize
map.setCenter(myLatlng)
});
//end of new code
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
clickable : true
});
It can be solved easily by re-initialize the Google Map on Tab click.
$('#kort').click(function(e) {
initialize();
resetMap(map);
});
This simple solution has found from here - How to Display Google Map Inside of a Hidden Div

Categories

Resources