【问题标题】:How to load Google Maps API with RequireJS?如何使用 RequireJS 加载 Google Maps API?
【发布时间】:2013-03-25 14:36:53
【问题描述】:

我正在努力使用 requireJS 加载 gmaps api。这是我尝试过的:

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) {})

但在 main.js 中,当我尝试实例化我得到的地理编码器时,未定义不是函数”错误。

var geocoder = new google.maps.Geocoder();

任何想法我可能做错了什么?

【问题讨论】:

  • 是否有网络错误?地图 api JS 真的在加载吗?
  • 没有它没有被加载...
  • 这个答案可能会有所帮助 - stackoverflow.com/questions/6398342/…。我没有 API 密钥,因此它可能无法完全为我工作。似乎必须请求加载地理编码器。
  • 能否请您展示您如何从 configure.js 中定义的 gmap 转到新的 google.maps.Geocoder()?

标签: google-maps-api-3 requirejs js-amd


【解决方案1】:

我已经设法用async 插件解决了这个问题。

一个简单的例子是:

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.
});

【讨论】:

  • 对我来说断点没有到达你评论的回调 //Google Maps...将在这里加载。
  • 如何安装异步插件?
【解决方案2】:

从 hjuster 开始,这里有一个如何使用 async 插件的快速示例

https://gist.github.com/millermedeiros/882682

【讨论】:

    【解决方案3】:

    还有goog 插件(需要异步和propertyParser),在github 上可用

    谷歌地图的使用示例:

    require(["goog!maps,3,other_params:sensor=false"], function(){});
    

    【讨论】:

    • 这就是这样做的方法。对我来说,它与谷歌地点一起工作没有问题:goog!maps,3,other_params:key=XXX&libraries=places
    【解决方案4】:

    感谢 user1706254 官方文档:https://github.com/millermedeiros/requirejs-plugins/ 使用的关键字“define”对我不起作用,但“require”工作正常。

    我无法直接加载:

    require(["goog!maps,3,other_params:sensor=false"], function(){});
    

    但是使用异步方式就可以了:

    require(['async!http://maps.google.com/maps/api/js?sensor=false'], function(){});
    

    【讨论】:

    • 嗯,它对我有用。 goog 模块要求在路径中定义“async”和“propertyParser”,就像这样,包括驼峰式大小写。顺便说一句,传感器现在什么都不做,可以省略
    • 任何人都可以获得 API 密钥来使用它吗?据我所知,这不支持在 URL 中包含 API 密钥。将一个硬编码到插件中并不难,但我认为这没有抓住重点。我现在更喜欢只使用异步模块来手动请求 url,因为这可以让你完全控制
    【解决方案5】:

    @hjuster 的回答引导我前进,我已经通过 回调函数 解决了。

    define(['async!http://maps.google.com/maps/api/js?key=YOURKEY!callback'],
        function (_ExpectedMap) {
                                  callback(); 
                               });
    

    注意 url 末尾的 !callbackasync! 开头,加载操作完成时正在调用回调方法。

    function callback()
    {
        //Now load google maps API dependant libraries
        require(['gmapsLib'], function (googlemaps) {
                         window.GMaps = googlemaps;
                       }
    }
    

    我最近注意到另一个question,另一个函数(onLoad)正在使用而不是回调以防止超时错误。很有趣。

    【讨论】:

      【解决方案6】:

      由于某种原因无法使插件工作,但这种解决方法挽救了我的一天:

       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();
        });
      });
      

      只需每 100 毫秒检查一次 gapi 是否准备就绪,直到它最终加载。

      找到本文代码http://dailyjs.com/2012/12/06/backbone-tutorial-2/

      我想你也可以试试

      if (google && google.maps && google.maps.Geocoder) {
          // now google.maps.Geocoder is gonna be defined for sure :)
      }
      

      【讨论】:

        【解决方案7】:

        您不需要异步插件即可通过 require.js 使用 Google 地图。只需使用简单的shim 配置即可实现目标:

        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>

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-05-09
          • 2011-02-25
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多