How to load Google Maps API with RequireJS? - google-maps-api-3

I am struggling to load gmaps api with requireJS . This is what I've tried:
requirejs.config({
urlArgs: "noCache=" + (new Date).getTime(),
paths : {
"jquery": "vendor/jquery-1.8.2.min",
"bootstrap": "vendor/bootstrap.min",
"underscore": "libs/underscore-min",
"backbone": "libs/backbone-min",
"template": "libs/template",
"gmaps": "http://maps.google.com/maps/api/js?v=3&sensor=false"
},
shim: {
'backbone': {
deps: ['jquery', 'underscore'],
exports: 'Backbone'
},
'underscore': {
exports: '_'
},
'bootstrap': {
deps: ['jquery']
},
'gmaps': {
deps: ['jquery']
},
'main':{
deps: ['jquery','gmaps']
}
}
});
require(["main"], function (main) {})
But inside main.js when I try to instantiate the geocoder i got ,,undefined is not a function" error.
var geocoder = new google.maps.Geocoder();
Any ideas what could I be doing wrong?

I've managed to sort it out with the async plugin.
A quick example is:
require.config({
paths: {
'async': 'lib/requirejs-plugins/src/async'
}
});
define(['async!http://maps.google.com/maps/api/js?sensor=false'], function() {
// Google Maps API and all its dependencies will be loaded here.
});

Thanks to user1706254 cause official documentation : https://github.com/millermedeiros/requirejs-plugins/ was using the keyword 'define' that wasn't working for me but 'require' is working fine.
I couldn't load directly :
require(["goog!maps,3,other_params:sensor=false"], function(){});
But using the asynchronous way did the trick :
require(['async!http://maps.google.com/maps/api/js?sensor=false'], function(){});

You don't need the async plugin to use Google Maps with require.js. The goal can be achieved using only a simple shim config:
require.config({
paths: {
gmaps: '//maps.googleapis.com/maps/api/js?' // question mark is appended to prevent require.js from adding a .js suffix
},
shim: {
gmaps: {
exports: 'google.maps'
}
}
});
require(['gmaps'], function (gmaps) {
var center = {lat: -34.397, lng: 150.644};
var map = new gmaps.Map(document.getElementById('map'), {
center: center,
zoom: 8
});
new gmaps.Marker({
map: map,
position: center
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.5/require.js"></script>
<div id="map" style="width: 100%; height: 200px"></div>

Following on from hjuster here's a quick example of how to use the async plugin
https://gist.github.com/millermedeiros/882682

There is also goog plugin (requires async and propertyParser), available on github
Usage example for google maps:
require(["goog!maps,3,other_params:sensor=false"], function(){});

#hjuster's answer led me the way and I've solved by a callback function.
define(['async!http://maps.google.com/maps/api/js?key=YOURKEY!callback'],
function (_ExpectedMap) {
callback();
});
Notice the !callback at the end of the url starts with async!, callback method is being called when load operation is done.
function callback()
{
//Now load google maps API dependant libraries
require(['gmapsLib'], function (googlemaps) {
window.GMaps = googlemaps;
}
}
There is another question I lately noticed, another function (onLoad) is in use instead of callback to prevent from timeout error. Interesting.

Couldn't make the plugins work for some reason, but this workaround saved my day:
require(['https://apis.google.com/js/client.js?onload=doNothing'], function() {
// Poll until gapi is ready
function checkGAPI() {
if (gapi && gapi.client) {
self.init();
} else {
setTimeout(checkGAPI, 100);
}
}
checkGAPI();
});
});
Just check if gapi is ready every 100 millisec, until it finally loads.
Found the code in this article http://dailyjs.com/2012/12/06/backbone-tutorial-2/
I guess you can also try it with
if (google && google.maps && google.maps.Geocoder) {
// now google.maps.Geocoder is gonna be defined for sure :)
}

Related

Why is data set with Meteor Iron Router not available in the template rendered callback?

This is a bit puzzling to me. I set data in the router (which I'm using very simply intentionally at this stage of my project), as follows :
Router.route('/groups/:_id',function() {
this.render('groupPage', {
data : function() {
return Groups.findOne({_id : this.params._id});
}
}, { sort : {time: -1} } );
});
The data you would expect, is now available in the template helpers, but if I have a look at 'this' in the rendered function its null
Template.groupPage.rendered = function() {
console.log(this);
};
I'd love to understand why (presuming its an expected result), or If its something I'm doing / not doing that causes this?
From my experience, this isn't uncommon. Below is how I handle it in my routes.
From what I understand, the template gets rendered client-side while the client is subscribing, so the null is actually what data is available.
Once the client recieves data from the subscription (server), it is added to the collection which causes the template to re-render.
Below is the pattern I use for routes. Notice the if(!this.ready()) return;
which handles the no data situation.
Router.route('landing', {
path: '/b/:b/:brandId/:template',
onAfterAction: function() {
if (this.title) document.title = this.title;
},
data: function() {
if(!this.ready()) return;
var brand = Brands.findOne(this.params.brandId);
if (!brand) return false;
this.title = brand.title;
return brand;
},
waitOn: function() {
return [
Meteor.subscribe('landingPageByBrandId', this.params.brandId),
Meteor.subscribe('myProfile'), // For verification
];
},
});
Issue
I was experiencing this myself today. I believe that there is a race condition between the Template.rendered callback and the iron router data function. I have since raised a question as an IronRouter issue on github to deal with the core issue.
In the meantime, workarounds:
Option 1: Wrap your code in a window.setTimeout()
Template.groupPage.rendered = function() {
var data_context = this.data;
window.setTimeout(function() {
console.log(data_context);
}, 100);
};
Option 2: Wrap your code in a this.autorun()
Template.groupPage.rendered = function() {
var data_context = this.data;
this.autorun(function() {
console.log(data_context);
});
};
Note: in this option, the function will run every time that the template's data context changes! The autorun will be destroyed along with the template though, unlike Tracker.autorun calls.

Meteor collection lookup on router level

I'm building an app that has versions of pages. I'd like users to be able to visit the page without having to specify the version they wish to start working with. In case no version is specified in the URL, I'd like to look up the latest version of that page and redirect to it.
The problem I'm having is that I can't do any collection lookups on the router level to figure out what version I'm looking for because the collections simply aren't there.
Here's my code so far:
Router.route('page', {
path: '/page/:slug/:version?',
onBeforeAction: function() {
var versionId = this.params.version;
if (!versionId) {
console.log('no version! oh noes!');
var p = Pages.find({slug: this.params.slug});
var newestVersion = Versions.findOne({page: p._id}, {sort: {createdAt: -1}});
versionId = newestVersion._id;
Router.redirect('page', this.params.slug, versionId);
}
this.next();
},
waitOn: function() {
return Meteor.subscribe('page', this.params.slug, this.params.state);
},
data: function() {
return {
page: Pages.findOne({slug: this.params.slug}),
version: Versions.findOne(this.params.version)
}
}
});
Any help or insights are very much appreciated!
Here's the solution I found. The problem is that the onBeforeAction didn't actually wait for the waitOn unless you tell it to.
onBeforeAction: function() {
if (this.ready()) {
if (!this.params.version) {
var p = Pages.findOne({slug: this.params.slug}),
sortedVersions = _.sortBy(Versions.find({page: p._id}).fetch(), function(s) {
return v.createdAt;
});
var newest_version_id = sortedVersions[0]._id;
this.redirect('page', {slug: this.params.slug, state: newest_version_id});
}
this.next();
}
}
I think the key is in the this.ready() check which is only true when all subscriptions in the waitOn are true. I assumed all this happened automagically by simply using the waitOn.

Server side rendering with Meteor and Meteorhacks:ssr and iron-router

This came out recently: https://meteorhacks.com/server-side-rendering.html but there doesn't seem to be a full fledged example of how to use this with iron-router.
If I had a template like:
/private/post_page.html
{{title}}
{{#markdown}} {{body}} {{/markdown}}
How would I populate it with a single records attributes from a request for a specific ID ?
E.g page requested was localhost:3000/p/:idofposthere how to populate it with data and render it in iron-router for that route / server side?
Actually a bit easier than you think (I just followed Arunoda's SSR example and converted it to iron-router for you):
if(Meteor.isServer) {
Template.posts.getPosts = function(category) {
return Posts.find({category: category}, {limit: 20});
}
}
Router.map(function() {
this.route('home');
this.route('view_post', {
path: 'post/:id',
where:"server",
action : function() {
var html = SSR.render('posts', {category: 'meteor'})
var response = this.response;
response.writeHead(200, {'Content-Type':'text/html'});
response.end(html);
}
});
});
It only gets tricky if you share the same route for client and server side for example, if you want it to render client-side based on user agent.
Source: We use this strategy on our own apps.
UPDATE
While the above code is simply what the question is asking for, we can get this working to follow Google's Ajax spec by checking the ?_escaped_fragment_= query string before we reach the client..
Basically, what we mostly don't know about Iron-Router is that if you have identical routes declared for server and client, the server-side route is dispatched first and then the client-side.
Here's the main javascript (with annotations):
ssr_test.js
Router.configure({
layout: 'default'
});
Posts = new Mongo.Collection('posts');
// Just a test helper to verify if we area actually rendering from client or server.
UI.registerHelper('is_server', function(){
return Meteor.isServer ? 'from server' : 'from client';
});
myRouter = null;
if(Meteor.isServer) {
// watch out for common robot user-agent headers.. you can add more here.
// taken from MDG's spiderable package.
var userAgentRegExps = [
/^facebookexternalhit/i,
/^linkedinbot/i,
/^twitterbot/i
];
// Wire up the data context manually since we can't use data option
// in server side routes while overriding the default behaviour..
// not this way, at least (with SSR).
// use {{#with getPost}} to
Template.view_post_server.helpers({
'getPost' : function(id) {
return Posts.findOne({_id : id});
}
});
Router.map(function() {
this.route('view_post', {
path: 'post/:id', // post/:id i.e. post/123
where: 'server', // this route runs on the server
action : function() {
var request = this.request;
// Also taken from MDG's spiderable package.
if (/\?.*_escaped_fragment_=/.test(request.url) ||
_.any(userAgentRegExps, function (re) {
return re.test(request.headers['user-agent']); })) {
// The meat of the SSR rendering. We render a special template
var html = SSR.render('view_post_server', {id : this.params.id});
var response = this.response;
response.writeHead(200, {'Content-Type':'text/html'});
response.end(html);
} else {
this.next(); // proceed to the client if we don't need to use SSR.
}
}
});
});
}
if(Meteor.isClient) {
Router.map(function() {
this.route('home');
this.route('view_post', { // same route as the server-side version
path: 'post/:id', // and same request path to match
where: 'client', // but just run the following action on client
action : function() {
this.render('view_post'); // yup, just render the client-side only
}
});
});
}
ssr_test.html
<head>
<title>ssr_test</title>
<meta name="fragment" content="!">
</head>
<body></body>
<template name="default">
{{> yield}}
</template>
<template name="home">
</template>
<template name="view_post">
hello post {{is_server}}
</template>
<template name="view_post_server">
hello post server {{is_server}}
</template>
THE RESULT:
I uploaded the app at http://ssr_test.meteor.com/ to see it in action, But it seems to crash when using SSR. Sorry about that. Works fine if you just paste the above on Meteorpad though!
Screens:
Here's the Github Repo instead:
https://github.com/electricjesus/ssr_test
Clone and run!
SSR is lacking real life examples, but here is how I got it working.
if (Meteor.isServer)
{
Router.map(function() {
this.route('postserver', {
where: 'server',
path: '/p/:_id',
action: function() {
// compile
SSR.compileTemplate('postTemplate', Assets.getText('post_page.html'));
// query
var post = Posts.findOne(this.params._id);
// render
var html = SSR.render('postTemplate', {title: post.title, body: post.body});
// response
this.response.writeHead(200, {'Content-Type': 'text/html'});
this.response.write(html);
this.response.end();
}
});
});
}
Assets are documented here: http://docs.meteor.com/#assets.

Spiderable and Iron-Router example

Does someone uses Iron-Router and Spiderable-404?
Please I need some complete examples to show me how to add the metatags.
They say this:
if (Meteor.isClient) {
Meteor.Router.add({
'/': 'index',
'/a': 'a',
'/b': function() {
Spiderable.httpHeaders['X-Foo'] = 'bar';
return 'b';
},
'*': function() {
Spiderable.httpStatusCode = 404;
return 'notFound';
}
});
}
but this does not work in iron router and there is no meta tag in this poor example, or I could not make it work, please help me fill the blanks.
The spiderable package is just a package you install and forget in Meteor. You do not use it directly from within your app.
Meteor SEO is not very mature, but you have options to get basic SEO working. Especially when you are using iron-router, there is the ms-seo smart package that you can use as:
$ mrt add ms-seo
and then in your router configuration:
Router.map(function() {
return this.route('blogPost', {
path: '/blog/:slug',
waitOn: function() {
return [Meteor.subscribe('postFull', this.params.slug)];
},
data: function() {
var post;
post = Posts.findOne({
slug: this.params.slug
});
return {
post: post
};
},
onAfterAction: function() {
var post;
// The SEO object is only available on the client.
// Return if you define your routes on the server, too.
if (!Meteor.isClient) {
return;
}
post = this.data().post;
SEO.set({
title: post.title,
meta: {
'description': post.description
},
og: {
'title': post.title,
'description': post.description
}
});
}
});
});
Also for 404 responses, iron-router's standard notFoundTemplate already provides the HTTP status code out of box. For other status codes, you need to define server side routes
````
Router.map(function () {
this.route('serverFile', {
where: 'server',
path: '/files/:filename',
action: function () {
var filename = this.params.filename;
this.response.writeHead(200, {'Content-Type': 'text/html'});
this.response.end('hello from server');
}
});
});
````
PS: You may want to refer to this blog post, and this one for further reading.
PPS: Your router configuration looks generally wrong. Your code looks like it belongs to the outdated meteor-router package. Refer to the iron-router package docs for more information.

What changes in the execution of an iron router route when coming in on a deep link?

I have a small meteor app going with iron router. Here's my routes.js, which is available to both client and server:
Router.configure({
layoutTemplate: 'defaultLayout',
loadingTemplate: 'loading'
});
// Map individual routes
Router.map(function() {
this.route('comicCreate', {
path: '/comic/create'
});
this.route('comicDetails', {
onBeforeAction: function () {
window.scrollTo(0, 0);
},
path: '/comic/:_id',
layoutTemplate: 'youtubeLayout',
data: function() { return Comics.findOne(this.params._id); }
});
this.route('frontPage', {
path: '/',
layoutTemplate: 'frontPageLayout'
});
this.route('notFound', {
path: '*',
where: 'server',
action: function() {
this.response.statusCode = 404;
this.response.end('Not Found!');
}
});
});
I need to feed some fields from my comic collection document into a package that wraps Youtube's IFrame API, and I'm doing this via the rendered function:
Template.comicDetails.rendered = function() {
var yt = new YTBackground();
if (this.data)
{
yt.startPlayer(document.getElementById('wrap'), {
videoIds: this.data.youtubeIds,
muteButtonClass: 'volume-mute',
volumeDownButtonClass: 'volume-down',
volumeUpButtonClass: 'volume-up'
});
}
};
This works great when I start by going to localhost:3000/ and then clicking on a link set to "{{pathFor 'comicDetails' _id}}". However, if I go directly to localhost:3000/comic/somevalidid, it doesn't, despite the fact that both routes end up pointing me at the same url.
The reason appears to be that when I go directly to the deep link, "this.data" is undefined during the execution of the rendered function. The template itself shows up fine (data correctly replaces the spacebars {{field}} tags in my template), but there's nothing in the "this" context for data when the rendered callback fires.
Is there something I'm doing wrong here?
try declaring the route in Meteor.startup ... not sure if that's the problem but worth a try

Resources