Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load Google Maps API with RequireJS?

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?

like image 918
hjuster Avatar asked Apr 03 '13 18:04

hjuster


People also ask

Can I use Google Maps API without API key?

In order to embed a Google Map iframe without api key add a Google Map widget from the left side panel. Then open it and add the address. This way you can embed Google Map without api key via Elementor.

Is Google Maps API no longer free?

You won't be charged until your usage exceeds $200 in a month. Note that the Maps Embed API, Maps SDK for Android, and Maps SDK for iOS currently have no usage limits and are at no charge (usage of the API or SDKs is not applied against your $200 monthly credit).


2 Answers

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. }); 
like image 77
hjuster Avatar answered Sep 29 '22 03:09

hjuster


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(){}); 
like image 39
hugsbrugs Avatar answered Sep 29 '22 04:09

hugsbrugs