Google Maps inside Ember.js - javascript

I've successfully managed to get Google Maps rendering on my main page. I'm using the same technique for one of my inner pages.
var MapView = Ember.View.extend({
layoutName: 'pagelayout',
didInsertElement : function(){
var mapOptions = {
center: new google.maps.LatLng(-34.397, 150.644),
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(this.$("#map").get(0),mapOptions);
this.set('map',map);
},
redrawMap : function(){
var newLoc = new google.maps.LatLng(this.get('latitude'), this.get('longitude'));
this.get('map').setCenter(newLoc)
}.observes('latitude','longitude')
});
However, it doesn't render. If I change it like so, it works but takes over the base html element.
this.$().get(0) /**from this.$('#map').get(0)**/
I'm quite stumped. Thinking that the problem might be that didInsertElement was being trigger way too early (I've understood it that the entire DOM for this View will be available when this event fires), I've tried setting up a afterRender listener and triggered the map load but that fails too. I've triple checked that the div exists.
Can someone please help me with this?

I ran the Google Maps init code from my console and found that the map did load so it seems to be an issue with how didInsertElement works with my setup. My understanding what that didInsertElement was called when the View was in the DOM but perhaps because I'm using layouts , it works differently.
I solved it by calling a separate view from within the div itself
{{#view "map"}}
and by creating a new View for the map.
var MapView = Ember.View.extend({
/**
Same as before
**/
});
This is just my solution that may be useful to others facing the same problem. If someone has a better solution, please add it so that I can verify and upvote it.

The this.$() might not be available as the view might not have rendered yet. Try wrapping it in a Ember.run.next call to delay the execution in the next run loop cycle:
didInsertElement: function() {
Ember.run.next(this, function() {
// your code
});
});

Related

Streetview Gives blackbox with Navbuttons, no street image, when loading

I'm using react to load streetview into a component I get this :
As we can see - the map component loads fine, and the streetview component seems to load fine, except that the image behind it (the actual street view) isn't loaded.
The error reported is :
**
Uncaught TypeError: Cannot read property 'toString' of undefined in
maps.googleapis.com/imagery_viewer.js:299
**
When I run similar code in straight-up HTML, this works ... sometimes ... often I get no returned image
I've isolated the code into a special function triggered with a large setTimeout() call so that the document load time is not to blame. Indeed, using watches and breakbpoints, we can see that the DIVs are loaded and accessible at run time.
handleLoad: ->
options = {
addressControl: true
fullscreenControl: true
panControl: true
pov: this.props.image.pov
visible: true
zoomControl: true
}
if this.props.image.pano
options.pano = this.props.image.pano
else if this.props.image.position
options.position = new google.maps.LatLng this.props.image.position[0], this.props.image.position[1]
if this.props.image.position
pos = new google.maps.LatLng this.props.image.position[0], this.props.image.position[1]
else
pos = {lat: this.props.entryLatitude, lng: this.props.entryLongitude};
options.key ='XXXX - GOOGLE MAP API KEY GOES HERE - XXXX';
this.map = new google.maps.Map(this.mapDiv, { center: pos, zoom: 14, visible:true } , streetViewControl: false);
this.panorama = new google.maps.StreetViewPanorama this.panoramaDiv, options;
this.map.setStreetView(this.panorama);
Any suggestions what could be causing this problem ?
This known black street view panorama issue can be cache or cors related. I suggest you first try ruling both of them out. E.g. see https://support.google.com/maps/thread/6166296?msgid=8836199
It may also be due to a third-party library bug or conflict. E.g. if you're using mootools or prototype.js check out these threads:
Mootools breaks Google maps streetview - black screen
https://issuetracker.google.com/issues/139252493
Another potential reason could be that your lat/lngs are far away from the roads where the street view imagery is available. Have a look at this great answer to related question Google map JS API "StreetViewPanorama" display black screen for some address
Let us know if any of the linked solutions work for you; otherwise please provide a codesandbox or stackblitz that reproduces the issue and I'll be happy to investigate further.

Leaflet: Force a map redraw from Layer extension

I am currently developing an extension to the L.TileLayer class, and from within the initialize method I would like to call a redraw on the map. My code looks like this:
L.TileLayer.NewLayerType = L.TypeLayer.extend({
_newLayerType: null,
initialize: function(file, options) {
var foo = new Foo(file, this, function(scope) {
...
scope.redraw();
});
L.Utils.setOptions(this, options);
},
...
});
The problem is, the scope.redraw() call does not work, nor does any other way of refreshing the map work outside of calling scope._map.zoomIn() and scope._map.zoomOut() immediately after. Is the redraw not working because the scope is a layer extension? What is the best way to do this?
Thanks

How to execute helper function after DOM is ready in meteor

I have a list of <li>'s which gets populated with a find() using Meteor.startup as you see below. Then I'm getting all the data attributes of these <li>'s using data() and putting it in an object and trying to return/console.log it so I can see if it works. But I'm getting null as a result.
Meteor.startup(function () {
Template.messages.lists = function () {
var allitems = lists.find();
return allitems;
};
var map;
map = new GMaps({
div: '#map_canvas',
lat: -12.043333,
lng: -77.028333
});
var lat = map.getCenter().lat();
var lng = map.getCenter().lng();
map.addMarker({
lat: lat,
lng: lng,
draggable: true,
title: 'Test',
dragend: function (e) {
$('#lat').val(this.getPosition().lat());
$('#lng').val(this.getPosition().lng());
}
});
console.log(getMarkers());
});
function getMarkers() {
var coordinates = {};
coordinates = $('li.message').data();
return coordinates;
}
I tried the same in my console directly and it works - I get an object back - so I'm guessing that the DOM is not ready/populated before this function is executed.
I am having a hard time understanding the difference between things like Meteor.startup and Template.mytemplate.rendered. In this case it seems that none of them works as I want?
What's the right way/place to do stuff with the DOM (traversing,getting attributes,manipulating)?
edit
as the code changed a lot in order to do what I wanted I post the whole thing.
Meteor.startup(function () {
var map;
map = new GMaps({
div: '#map_canvas',
lat: 50.853642,
lng: 4.357452
});
Meteor.subscribe('AllMessages', function() {
var allitems = lists.find().fetch();
console.log(allitems);
allitems.forEach(function(item) {
var lat = item.location.lat;
var lng = item.location.lng;
console.log('latitude is: ' + lat);
console.log('longitude is: ' + lng);
map.addMarker({
lat: lat,
lng: lng,
draggable: true,
title: 'Test',
dragend: function(e) {
$('#lat').val(this.getPosition().lat());
$('#lng').val(this.getPosition().lng());
}
});
});
});
});
The above code creates a new google map (using the GMaps.js plugin) inside Meteor.Startup, and then in a nested Subscribe fetchs all documents from a collection, forEaches the results and gets the latitude and longitude values, then goes on to add markers in the google map...
edit 2
I made my 'map' variable a global one this way no need to nest .subscribe and .startup. :
Meteor.subscribe('AllMessages', function() {
var allitems = lists.find().fetch();
console.log(allitems);
allitems.forEach(function(item) {
var lat = item.location.lat;
var lng = item.location.lng;
console.log('latitude is: ' + lat);
console.log('longitude is: ' + lng);
map.addMarker({
lat: lat,
lng: lng,
draggable: true,
title: item.description,
dragend: function(e) {
$('#lat').val(this.getPosition().lat());
$('#lng').val(this.getPosition().lng());
}
});
});
});
Meteor.startup(function () {
map = new GMaps({
div: '#map_canvas',
lat: 50.853642,
lng: 4.357452
});
});
Template.messages.lists = function () {
var allitems = lists.find().fetch();
return allitems;
}
Meteor.startup
Meteor.startup() runs only once, its run on the client and server. So when the browser loads and the initial DOM is ready or the server starts. As Sohel Khalifa said you place initialization functions here. Don't define templates in here because the the templates need to be ready before this function can be fired.
Template.myTemplate.onRendered(function() {... })
This is run when meteor has finished and rendered the DOM. Additionally is run each time the HTML changes within the template. So for each item in your list in a subtemplate/a change in an item/update,etc as well as the list you will see the console.log return something if you use it to check. It will return null/undefined when calling for data sometimes (which i'll explain):
Does this mean all the DOM is ready? NO!:
I think this is what might be causing you a bit of trouble. If you use external APIs such as Google maps, they might still render the map. the Template.myTemplate.rendered() means Meteor has finished rendering the template with the reactive variables necessary. So to find out when your Google maps might be ready you need to hook into the Google maps API. Have a look at this question
Using Meteor.subscribe
The reason you might get null/undefined while using rendered is because this is the process meteor usually renders data into templates
You are basically calling console.log(getMarkers()); before the subscription is complete, which is why you get null/undefined
Meteor uses this summarized process with templates & reactive data:
Build Templates with no data & render - NO data yet at this stage
Ask server for data in collections
Rebuild templates with new data & render
So if at process 1) for a very short time you will have no data yet, which is why you might get null (such as in your code) & at the first render. To get past this you should use Meteor.subscribe's callback which is run when all the data is downloaded from the server: e.g
Meteor.subscribe("lists", function() {
//Callback fired when data received
});
Note: Before you use this you should read the docs on using subscriptions as you need to remove the autopublish package, as well as make a corresponding Meteor.publish function on the server. While this may seem tedious you may end up doing it anyway to give your users their own lists &/or implement some kind of security.
Suggested edits to your code:
You are doing DOM traversing in the right place, Template.mytemplate.onRendered(function().. but you also need to hook into Google Maps' API to capture when their map is finished drawing. You should also use Meteor.subscribe to make sure you get the timing right and not get null/undefined.
Make sure you put your Template helpers in a Meteor.isClient but not in a Meteor.startup because Meteor.startup is fired after your initial DOM is ready (the intitial is the first but before its changed by reactive variables or a router) so your template definitions need to run before this stage.
The reason why it returns null as a result is, you have placed it in Meteor.startup(). It actually runs before the data is loaded from the server. So the lists.find() returns null.
The Meteor.startup() is a place for initializing your global variables, reative sessions and subscribing to the primary bunch of data from the server. Everything you write there will be executed once, right after the client starts up.
The Template.myTemplate.rendered() is a special helper provided by meteor that runs everytime when the corresponding data has changed, it is mainly used for getting attributes or manipulating DOM elements contained within that template.
So, place your helper code outside in common isClient() area. And use .rendered()helper to traverse the DOM, and getting or manipulating attributes of DOM elements.
Many thanks Akshat for detailed answer)
I have more complicated case of using Meteor.subscribe, i have template which includes images from DB. So i need to wait for data from two collection iamges and news(all other data here).
I get my DOM ready in this way:
imageIsLoaded = new Promise(function(resolve){
Meteor.subscribe('images',function(){
resolve()
});
});
newsIsLoaded = new Promise(function(resolve){
Meteor.subscribe('news',function(){
resolve()
});
});
Template.newsList.onRendered(function(){
Promise.all([imageIsLoaded, newsIsLoaded]).then(function() {
// DOM IS READY!!!
newsServices.masonryInit();
})
});
Template structure:
<template name="newsList">
{{#each news}}
{{> news_item}}
{{/each}}
</template>
The best way to do this is to put code into Template.x.rendered() and use a Session reactive variable to track if the code has been run or not. For example, you could go about this like so:
Template.x.rendered = function () {
if (Session.get('doneMarkers') == null) {
// Do your stuff
if (getMarkers() != null) {
Session.set('doneMarkers', 'yes');
}
}
});
function getMarkers() {
var coordinates = {};
coordinates = $('li.message').data();
return coordinates;
}
If you ever want to rerun that part of the code, you only have to call:
Session.set('doneMarkers', null);

Googlemaps API very slow when initialized from window.onload

To avoid an ie 7/8 "unspecified error", I recently moved the initialization logic for a JSON powered GoogleMaps v3 implementation from inline following $(document).ready to within an event function triggered from window.onload(). Now, what was once a very fast load is now taking 15-20 seconds + to load. I understand that there are some subtle differences between oninit and onload, but this seems extreme. Any thoughts?
$(document).ready(function(){
var branchitems=[];
var markers=[];
var map="";
window.onload = function() {
var latlng = new google.maps.LatLng(59.5, -100.68);
var myOptions = {
zoom: 3,
center: latlng,
mapTypeId: google.maps.MapTypeId.TERRAIN
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
PopulateMap(map);
}
function PopulateMap(map){
... my logic for the JSON portion of the map ...
};
window.onload is the right place to put this if you're loading the API synchronously, otherwise your code may execute before the Maps API has downloaded.
If this is taking 10 - 15 seconds then it is likely that you are loading a bunch of other resources as well. window.onload won't execute until everything has finished downloading (e.g. all scripts in script tags).
One solution may be to load Maps API V3 asynchronously (see: http://code.google.com/apis/maps/documentation/javascript/basics.html#Async). You can then start constructing your map as soon as the API has loaded.
An alternate solution is to asynchronously load anything that you don't need to be ready as soon as a user visits the site, or to load your resources from faster locations (e.g. load jQuery from the Google CDN instead of from your own server).

Avoid hanging when closing a Yahoo map with lots of markers

I have a Yahoo map with lots of markers (~500). The map performs well enough until I close the page, at which point it pauses (in Firefox) and brings up a "Stop running this script?" dialog (in IE7). If given long enough the script does complete its work.
Is there anything I can do to reduce this delay?
This stripped down code exhibits the problem:
<script type="text/javascript">
var map = new YMap(document.getElementById('map'));
map.drawZoomAndCenter("Algeria", 17);
for (var i = 0; i < 500; i += 1) {
var geoPoint = new YGeoPoint((Math.random()-0.5)*180.0, (Math.random()-0.5)*360.0);
var marker = new YMarker(geoPoint);
map.addOverlay(marker);
}
</script>
I'm aware of some memory leaks with the event handlers if you're dynamically adding and removing markers, but these are static (though the problem may be related). Oh, and I know this many markers on a map may not be the best way to convey the data, but that's not the answer I'm looking for ;)
Edit: Following a suggestion below I've tried:
window.onbeforeunload = function() {
map.removeMarkersAll();
}
and
window.onbeforeunload = function() {
mapElement = document.getElementById('map');
mapElement.parentNode.removeChild(mapElement);
}
but neither worked :(
Use Javascript profiler and see which function is slow. Then you'll have better idea how to make a workaround or at least how to remove expensive cleanup (and let it leak in IE6).
You could try removing all the markers, or even removing the map from the DOM using the "onbeforeunload" event.
Are you sure nothing is tryin to access the map , when you close the window?
I'd do this type of test:
have a wrapper to reach the map itself, and, on unload, have the wrapper block access to map itself.

Categories