Q: How to intercept GoogleMap's requestAnimationFrame using Zone.js - google-maps

EDIT: I'm using Zone v0.8.20
Background: Google Maps triggers requestAnimationFrame when zooming out of the map and when panning, I want to intercept these requestAnimationFrame via Zone.js to debounce it and may be improve performance on mobile devices...
I have the following simple repro code:
<!DOCTYPE html>
<html>
<head>
...
<script src="node_modules/zone.js/dist/zone.js"></script>
</head>
<body>
<div id="map"></div>
<script>
var map;
var mapZone = Zone.current.fork({
name: "GMAPS",
onScheduleTask: (delegate, current, target, task) => {
console.log(task);
console.log(Zone.current.name)
return delegate.scheduleTask(target, task);
},
onHasTask: (delegate, current, target, task) => {
console.log(task)
}
})
function initMap() {
mapZone.run(() => {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -34.397, lng: 150.644},
zoom: 8
});
var marker = new google.maps.Marker({
position: {lat: -34.100, lng: 150.644},
map: map,
title: 'Hello World!'
});
});
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=API_KEY&callback=initMap&sensor=true"
async defer></script>
</body>
</html>
The problem here is that I can't seem to intercept the requestAnimationFrame on the onScheduleTask method defined on the ZoneSpec... as you can see on the code, I ran the instantiation of Google Maps inside the forked Zone called mapZone
I'm newbie on Zone.js, this probably might be a simple problem, but I can't seem to find a solution... what do you think am I missing here?
Thanks so much in advance!

the reason that it is not work because google map is loaded in root zone, and in current version of zone.js, there are no way to configure the root zone spec.
I have created a walk around about this one to config root zone by monkey-patch zone.js. you can find the working sample in below link.
https://github.com/JiaLiPassion/customize-root-zone

Related

loading google map from another component with vue router

I have an issue about google map loading. the thing is in #App component reading google map
component from <router-view> but with this way it's giving the error: "ReferenceError: google is not defined". first I thought I am missing something inside initMap() but no, because if I try to paste map method into the app.vue then google map running without a problem.
By the way my api is inside the public/index.html
<script async defer src="https://maps.googleapis.com/maps/api/js?key=MY_API&callback=initMap"></script>
the map.vue component:
<template>
<div id="map" class="map"></div>
</template>
<script>
export default {
mounted(){
this.initMap();
},
methods: {
initMap(){
let options = {
center: {lat: 34.693725, lng: 135.502254},
zoom: 15,
mapTypeId: "roadmap"
};
let map = new google.maps.Map(document.getElementById("map"), options);
}
}
}
</script>
so what do you think problem is and how can I map component work with the <router-view>
The Vue Cookbook has an example for loading google maps, which uses google-maps-api-loader to wrap the loading process into a promise.
The promise from the loader is awaited in the mount hook in the consuming component.
Here's a codesandbox demonstrating the approach.

window.Map is not a constructor in Google Maps API v3

I have a google map with a new key
but it gets error in console
error:
Uncaught TypeError: window.Map is not a constructor
at Zr (map.js:2)
at ds.release (map.js:53)
at gs (map.js:5)
at _.rl.Ab (map.js:59)
at map.js:46
HTML
<head>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=mykey">
</script>
</head>
<body onload="init()">
<div id="map_canvas"></div>
</body>
<script src="js/index.js"></script>
index.js
Map = null;
function init() {
var mapOptions = {***};
Map = new google.maps.Map( document.getElementById( "map_canvas" ), mapOptions );
}
Thanks for your time!
Map is reserved word in EcmaScript, so you shouldn't use it as a variable name: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map
The problem is this line (jsfiddle thinks Map is read only):
Map = null;
Rename your map variable to something else (like map, with a lower case "m").
proof of concept fiddle
code snippet:
map = null;
function init() {
var mapOptions = {
center: {
lat: 0,
lng: 0
},
zoom: 1
};
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
}
google.maps.event.addDomListener(window, "load", init);
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>
This is a problem with the weekly version of maps this week. I changed:
...//maps.googleapis.com/maps/api/js?key....
to
...//maps.googleapis.com/maps/api/js?v=3.34&key...
the first path server the weekly version of maps which is default.
I chose it to set the version to 3.34 which worked fine. I could have chosen a quarterly version which would update automatically to the version of the current quarter(it would automatically update next quarter) by inserting v=quarterly. Either way the 3.34 fixed my issues.

Using freemarker 'list' directive within a google maps function

I have the following list called 'locationList':
[[lat:-6.2986514, lng:53.3324511, car_reg:161-D-XXXXXX], [lat:-7.259881, lng:53.041335, car_reg:151-D-YYYYY], [lat:-7.6273397, lng:53.3052366, car_reg:142-D-ZZZZZ]]
Now, if I just do a simple iteration like this it works. (It outputs my three lines of coordinates.).
<#list locationList as loc>
<p> Output: ${loc.lat} -- ${loc.lng} </p>
</#list>
But when I try to use it within my google maps function, it won't work. This is what I have:
function geocodeLatLng(geocoder, map, infowindow) {
<#list locationList as loc>
var latlng = {lat: ${loc.lat}, lng: ${loc.lng} };
var marker = new google.maps.Marker({
position: latlng,
map: map
});
</#list>
}
It works fine if I just write out manually three times what is contained within the freemarker list tags.
And I have tried everything I can think of. Can anyone help throw light on what is happening here?
EDIT - Whole script included below:
<script>
function initMap() {
<#assign lat='53.328015' lng='-6.3743767' >
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 8,
center: {lat: ${lat}, lng: ${lng} }
});
var geocoder = new google.maps.Geocoder;
var infowindow = new google.maps.InfoWindow;
google.maps.event.addDomListener(window, 'load', function() {
geocodeLatLng(geocoder, map, infowindow);
});
}
function geocodeLatLng(geocoder, map, infowindow) {
<#list locationList as loc>
var latlng = {lat: ${loc.lat}, lng: ${loc.lng} };
var marker = new google.maps.Marker({
position: latlng,
map: map
});
</#list>
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=REMOVED&callback=initMap"
async defer></script>
In cases like this, always check what the actual output is (you should be able to do that in the web browser) and how that differs from what you write when you fill it manually. Also, check what JavaScript errors you get.
My blind guess is that the numbers are formatted for human audience, and thus aren't valid JavaScript literals. Use ?c (as in ${loc.lat?c}) to format for computer "audience".
The code was fine. In constructing my list I had got longtitude and latitude the wrong way around. Apologies. I was looking in the entirely wrong place.

Collaborative Realtime Mapping with Firebase Heatmap not working

I tried the tutorial from this place.
When I get at the heatmap part it doesn't draw the map anymore.
I guess I must be doing something wrong but I have no clue...
The moment I remove the comments from icon: image part I'll get a map drawn,
but the heatmap part isn't working.
I hope that somebody can help me
Kind Regards
Guy
// Reference to the Firebase database.
var firebase = new Firebase("https://adopt-a-portal.firebaseio.com/");
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 0, lng: 0},
zoom: 3
});
// Add marker on user click
map.addListener('click', function(e) {
firebase.push({lat: e.latLng.lat(), lng: e.latLng.lng()});
});
// Create a heatmap.
var heatmap = new google.maps.visualization.HeatmapLayer({
data: [],
map: map,
radius: 8
});
firebase.on("child_added", function(snapshot, prevChildKey) {
// Get latitude and longitude from Firebase.
var newPosition = snapshot.val();
// Create a google.maps.LatLng object for the position of the marker.
// A LatLng object literal (as above) could be used, but the heatmap
// in the next step requires a google.maps.LatLng object.
var latLng = new google.maps.LatLng(newPosition.lat, newPosition.lng);
// Place a marker at that location.
var image = 'https://developers.google.com/maps/documentation/javascript/examples/full/images/beachflag.png';
var marker = new google.maps.Marker({
position: latLng,
map: map
// icon: image
});
heatmap.getData().push(latLng);
});
}
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
html, body { height: 100%; margin: 0; padding: 0; }
#map { height: 100%; }
</style>
<script src="https://cdn.firebase.com/js/client/2.2.1/firebase.js"></script>
</head>
<body>
<div id="map"></div>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyABc8Rw-DxVzajwPZ8C90cfFT69LfAec6o&region=BE&callback=initMap"
async defer></script>
<script src="map.js"> </script>
</body>
</html>
I get a javascript error with your code: Uncaught TypeError: Cannot read property 'HeatmapLayer' of undefined
You aren't including the visualization library.
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyABc8Rw-DxVzajwPZ8C90cfFT69LfAec6o&region=BE&callback=initMap"
async defer></script>
Should be (note the added "libraries=visualization"):
<script src="https://maps.googleapis.com/maps/api/js?libraries=visualization&key=AIzaSyABc8Rw-DxVzajwPZ8C90cfFT69LfAec6o&region=BE&callback=initMap"
async defer></script>
proof of concept fiddle

Google Maps API v3: Gray Box, no map

As part of a much bigger project, we're trying to get a Map on a site using Google's Map API v3. I have followed the simplest steps that Google has laid out, I've tried copying code outright from other working maps. But no matter what I do, all we get is a gray box and no map.
Using Firebug, I can see the information trying to populate the map, but it is simply not displaying. I've tried jquery, jquery libraries specifically made for google maps, nothing is working. I have been up and down the internet and all through google's api help files. Plus, the problem is not local as I've uploaded the file to multiple servers and tested it on multiple browsers and computers. Nothing is working.
At this point it's got to be something stupid that I'm overlooking. Here's my code.
<!DOCTYPE html>
<html>
<head>
<title></title>
<META NAME="ROBOTS" CONTENT="NOINDEX, NOFOLLOW">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?&sensor=true">
</script>
<script type="text/javascript">
function load()
{
var mapDiv = document.getElementById("map");
var latlng = new google.maps.LatLng(-34.397, 150.644);
var mapOptions =
{
//zoom: 8,
center:latlng,
//backgroundColor: '#ff0000',
mapTypeId: google.maps.MapTypeId.ROADMAP,
imageDefaultUI: true
};
var map = new google.maps.Map(mapDiv, mapOptions);
function createMarker(point, text, title)
{
var marker =
new GMarker(point,{title:title});
return marker;
}
}
</script>
</head>
<body onload="load()">
<div id="map" style="width: 800px; height: 400px;"></div>
</div>
</body>
</html>
This works for me. You simply have to set zoom parameter:
UPDATE (by #user2652379): You need to set BOTH zoom and center options. Just zoom does not work.
<!DOCTYPE html>
<html>
<head>
<title></title>
<META NAME="ROBOTS" CONTENT="NOINDEX, NOFOLLOW">
<script src="http://maps.google.com/maps/api/js?sensor=false" type="text/javascript"></script>
</script>
<script type="text/javascript">
function load()
{
var mapDiv = document.getElementById("map");
var latlng = new google.maps.LatLng(-34.397, 150.644);
var mapOptions =
{
zoom: 8,
center:latlng,
//backgroundColor: '#ff0000',
mapTypeId: google.maps.MapTypeId.ROADMAP,
//imageDefaultUI: true
};
var map = new google.maps.Map(mapDiv, mapOptions);
// map.addControl(new GSmallMapControl());
// map.addControl(new GMapTypeControl());
// map.addMapType(ROADMAP);
// map.setCenter(
// new GLatLng(37.4419, -122.1419), 13);
}
</script>
</head>
<body onload="load()">
<div id="map" style="width: 800px; height: 400px;"> </div>
</body>
</html>
Another case is when map container is hidden at the moment you initialize the map. E.g. you are doing it inside bootstrap show.bs.modal event, instead of shown.bs.modal
I had the same issue and came across a lot of topics on stackoverflow but none of them had the working solution for me. I eventually found out it was caused to a line of css I had added.
All the elements in the map inherited a
overflow:hidden;
By adding the following line to my CSS it was fixed
#map * {
overflow:visible;
}
I would like to add a quick comment to this since I had the same problem with the zoom parameter set.
I found out that the problem was my theme's css. In my base theme I had the following CSS:
img, embed, object, video {
max-width: 100%;
max-height: 100%;
width: auto;
height: auto;
}
This messed up the rendering of the map and after I removed it, my map renders just fine.
Also beware of having an invalid latitude or longitude value for the map center or your markers. For example, this fiddle shows the Grey Map Of Death because the map center is at latitude 131.044 which is invalid (not from +90:-90).
function initMap() {
var uluru = {lat: 131.044, lng: -25.363};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: uluru
});
var marker = new google.maps.Marker({
position: uluru,
map: map
});
}
In my case, I was working on a map with vue and a modal in the iview library; and during the first render it worked, but any other render displayed the grey screen of death. I fixed the issue by setting a timeout function to display the map after 50 ms to give the modal enough time to render and be visible.
//Time out is crucial for the map to load when opened with vue
setTimeout(() => {
this.showMap(id);
}, 50);
The above example was an earlier fix and a quick hack, i have realized all you need to do is wait for the next tick, on vue you can achieve this by
async mounted(){
await this.$nextTick()
this.showMap(id)
}
or if you are not comfortable with async await you can try the callback option
mounted(){
Vue.nextTick(function () {
this.showMap(id)
})
}
I had the same issue. i was using google maps in Jquery Accordion and when i expand the div the map only consisted a grayed area. I was able to solve this issue by triggering a click event on the specified accordion heading and setting the map container to visible.
Script:
<script type="text/javascript">
var map;
function initMap(lat, lng) {
var myCenter = new google.maps.LatLng(lat, lng);
var mapOptions = {
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: myCenter
};
map = new google.maps.Map(document.getElementById('map'), mapOptions);
}
function ViewMap() {
var latlng = document.getElementById('<%=txt.ClientID%>').value.split(','); // This is where my latlng are placed: 25.12312,55.3212333
$("#showmap").show();
// Sorry for mixing up Jquery and javascript.
initMap(latlng[0], latlng[1]);
}
</script>
ASPX File/Html Markup:
<h3 id="lMap" onclick="ViewMap();"><i class="fa fa-map-o" onclick="ViewMap();"></i>Location Map</h3>
<div style="height:auto" id="showmap">
<div id="map" style="width: 850px; height: 550px; overflow: visible"></div>
</div>
I realise this is an old thread, but this may help someone in the future.
Struggled with this for hours, but after discovering that the Google Map is rendered with a grey box overlay if the map is rendered while not being visible, I used a bit of jQuery to make my application only instantiate and render the map if the map is visible, like such:
if ($("#myHomeMapHolder").is(":visible")) {
if (homemap == null) {
homemap = new google.maps.Map(document.getElementById("myHomeMapHolder"), myOptions);
google.maps.event.addListener(homemap, 'click', function (event) {
placeHomeMarker(event.latLng);
});
} else {
homemap.setCenter(myLatlng);
}
if (homemarker == null) {
homemarker = new google.maps.Marker({
position: myLatlng,
map: homemap,
title: "Home"
});
} else {
homemarker.setPosition(myLatlng);
}
}
And voila, my map is only rendered if the map holder is visible, so it never renders with a grey box.
For anyone wondering, myHomeMapHolder is a div which the map sits inside.
In my case, someone had dropped this little prize in some responsive.css file:
img {
max-width: 100% !important;
}
Removed that and all is fine now.
I had this issue with a site I'm working on too. We're doing some things to all <img> tags for responsiveness. This fix is working for us for the map:
img {max-width: initial !important;}
For those who might be stuck regardless of the nice solutions provided here, try setting the height and width of your container directly in the html markup instead of a stylesheet ie.
<div id="map-container" style="width: 100%; height: 300px;"></div>
happy mapping!
This may not be the case for everyone, but maybe it can help someone.
I was creating markers in my map from data attributes placed on the map element like this: data-1-lat="2" data-1-lon="3" data-text="foo". I was putting them in an array based on the order they were placed in the data attributes.
The problem is that IE and Edge (for some mad reason) invert the order of the data attributes in the HTML tag, therefore I wasn't able to correctly extract them from the data attributes.
None of the existing answers helped me because my problem was that Apollo was adding extra properties ("__typename" fields) to my MapOptions object.
In other words, the JSON looked like this:
mapOptions {"__typename":"MapOptions","center":{"__typename":"GeoCoordinates","lat":33.953056,"lng":-83.9925},"zoom":10}
Once I realized that those extra properties were problematic, this is how I solved it (using TypeScript):
function getCleanedMapOptions(mapOptionsGql: google.maps.MapOptions): google.maps.MapOptions {
const mapOptions = { ...mapOptionsGql };
const lat: number = mapOptions.center.lat as number;
const lng: number = mapOptions.center.lng as number;
const mapOptionsCleaned = {
center: new google.maps.LatLng({ lat, lng }),
zoom: mapOptions.zoom,
};
return mapOptionsCleaned;
}
export function createMap(mapOptions: google.maps.MapOptions): google.maps.Map {
const mapOptionsCleaned = getCleanedMapOptions(mapOptions);
const map = new google.maps.Map(document.getElementById('map') as HTMLElement, mapOptionsCleaned);
return map;
}
In my case (version is 3.30 when submitting this), it was because the div id MUST be "map"
<div id="map"></div>
...
document.getElementById("map")