如何在Web应用程序的单独文件中对Google Maps init进行回调 [英] How to make a callback to Google Maps init in separate files of a web app

查看:127
本文介绍了如何在Web应用程序的单独文件中对Google Maps init进行回调的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的Google Maps API代码片段中:

 < script async defer src =https:// maps。 googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap\"></script> 

位于 index.html 中,错误:未捕获InvalidValueError:initMap不是函数



我想保留所有的 bower_component ,我的 index.html 我的Yeoman脚手架AngularJS web应用程序中的CSS,API和脚本声明。我实际尝试重新创建的地图将位于另一条路线上,我们称之为routeafterlogin,然后是基本地图。我把js和html html组件分隔成 afterlogin.js afterlogin.html



这有很多可能的原因。其中之一是为了调整匹配命名空间的问题而提出的, https://stackoverflow.com/a/34466824/ 1923016 。这是否需要角度服务?如果是这样,服务将如何工作到 initMap 函数中,并在Google maps api snippet中调用它?



其中一个并发症是命令。我是新开发的web应用程序开发人员,但是从我可以告诉 index.html 首先加载,使用代码段中的url来回调<$ c < code>< script> ...< / script> 中未包含$ c> initMap index.html 文件,也不在 app.js 文件中。相反,由于init函数在路由的js代码中,因此无法看到,因此需要某种命名空间版本的调用。这甚至会从登录路线导致控制台错误,甚至不是地图的 div

----编辑:----



另请注意,在这种情况下,这并没有诀窍:

  window.initMap = function(){
//。 ..
}

这也不适用,因为函数永远不会被调用:<一个href =https://stackoverflow.com/questions/36795150/uncaught-invalidvalueerror-initmap-is-not-a-function>未捕获的InvalidValueError:initMap不是一个函数




$ b afterlogin.js
($'$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $' b
函数initMap(){
var map = new google.maps.Map(document.getElementById('map'),{
zoom:17,
center:{lat :-33.8666,lng:151.1958}
});

var marker = new google.maps.Marker({
map:map,
//定义有位置的地方,和aq uery字符串。
地方:{
位置:{lat:-33.8666,lng:151.1958},
查询:'Google,Sydney,Australia'

},
//归因可帮助用户再次找到您的网站。
署名:{
来源:'Google Maps JavaScript API',
webUrl:'https://developers.google.com/maps/'
}
} );

//构建一个新的InfoWindow。
var infoWindow = new google.maps.InfoWindow({
content:'Google Sydney'
});

//点击标记时打开InfoWindow。
marker.addListener('click',function(){
infoWindow.open(map,marker);
});
}
});

afterlogin.html

 <!DOCTYPE html> 
< html>
< head>
< title>登录后页面< / title>
< meta name =viewportcontent =initial-scale = 1.0,user-scalable = no>
< meta charset =utf-8>
< style>
html,body {
height:100%;
保证金:0;
padding:0;
}
#map {
height:100%;
}
< / style>
< / head>
< body>

< div id =map>< / div>

< / body>
< / html>


解决方案

由于Google Maps SDK脚本会加载同步 async 属性),URL中有 callback 参数。



为了解决这个问题,您需要了解google sdk中的 async 机制


异步属性可让浏览器在Maps JavaScript API加载时呈现网站的其余部分。当API准备就绪时,它将调用使用callback参数指定的函数。


https://developers.google.com/maps/documentation/javascript/tutorial#Loading_the_Maps_API



所以解决方案是加载脚本synchronic:


在加载Maps JavaScript API的脚本标记,可以省略async属性和回调参数。这会导致API的加载被阻止,直到下载API。



这可能会减慢你的页面加载速度。但它意味着你可以编写后续脚本标签,假设API已经被加载。


https://developers.google.com/maps/documentation/javascript/tutorial#sync


  1. 您可以通过这种方式移除 async 属性,页面将停止运行直到脚本完成下载并在页面上运行。因此,当浏览器访问您的代码时,所有SDK对象都可用。
  2. 现在,因为没有调用 initMap 的代码, code>函数(记住:谁叫它,它是只在 async 模式中调用它的sdk脚本),你需要自己调用它。所以,只需在控制器的最后调用它即可。


When I had my Google Maps API snippet:

<script async defer src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap"></script>

in index.html, I got the error: Uncaught InvalidValueError: initMap is not a function.

I want to keep all of my bower_component, CSS, API, and script declarations in my index.html file on my Yeoman-scaffolded AngularJS web app. The map I was actually trying to recreate would be on another route, let's call it route "afterlogin", just a basic map. I separated the js and the html html components into afterlogin.js and afterlogin.html

There are a number of potential causes for this. One of which was presented here as a matter of adjusting the call to match the namespace, https://stackoverflow.com/a/34466824/1923016 . Would this require an angular service? If so, how would the service work into the initMap function and its call in the Google maps api snippet?

One of the complications is the order. I'm new to web app dev, but from what I can tell the index.html loads first, uses the url in the snippet to make the callback to the initMap function which is not featured in <script>...</script> in the index.html file nor in the app.js file. Instead, since the init function is in a route's js code, it cannot be seen, hence the need for some kind of "namespace" version of the call. This leads to a console error even from the login route, which is not even where the div for the map is.

---- EDIT: ----

Also note that in this case, this did not do the trick:

window.initMap = function(){
//...
}

This also does not apply, as the function is never called: Uncaught InvalidValueError: initMap is not a function

-- -- -- -- -- --

afterlogin.js

angular.module('myappproject').controller('AfterloginCtrl', function ($scope) {

  function initMap() {
    var map = new google.maps.Map(document.getElementById('map'), {
      zoom: 17,
      center: {lat: -33.8666, lng: 151.1958}
    });

    var marker = new google.maps.Marker({
      map: map,
      // Define the place with a location, and a query string.
      place: {
        location: {lat: -33.8666, lng: 151.1958},
        query: 'Google, Sydney, Australia'

      },
      // Attributions help users find your site again.
      attribution: {
        source: 'Google Maps JavaScript API',
        webUrl: 'https://developers.google.com/maps/'
      }
    });

    // Construct a new InfoWindow.
    var infoWindow = new google.maps.InfoWindow({
      content: 'Google Sydney'
    });

    // Opens the InfoWindow when marker is clicked.
    marker.addListener('click', function() {
      infoWindow.open(map, marker);
    });
  }
 });

afterlogin.html

<!DOCTYPE html>
<html>
    <head>
        <title>after login page</title>
        <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
        <meta charset="utf-8">
        <style>
            html, body {
                height: 100%;
                margin: 0;
                padding: 0;
                }
            #map {
                height: 100%;
            }
        </style>
    </head>
    <body>

        <div id="map"></div>

    </body>
</html>

解决方案

Since the Google Maps SDK script load a synchronic (due the async attribute), there is the callback parameter in the URL.

To solve the problem, you need to understand the async mechanism in google sdk

The async attribute lets the browser render the rest of your website while the Maps JavaScript API loads. When the API is ready, it will call the function specified using the callback parameter.

https://developers.google.com/maps/documentation/javascript/tutorial#Loading_the_Maps_API

So the solution is to load the script synchronic:

In the script tag that loads the Maps JavaScript API, it is possible to omit the async attribute and the callback parameter. This will cause the loading of the API to block until the API is downloaded.

This will probably slow your page load. But it means you can write subsequent script tags assuming that the API is already loaded.

https://developers.google.com/maps/documentation/javascript/tutorial#sync

  1. You can remove the async attribute that way, the page will stop running until the script will complete downloaded and run on the page. So, when the browser will get to your code, all the SDK object will be available.
  2. Now, since there is not code that calls to the initMap function (remember: who called it, it was the sdk script which call it only in the async mode), you need to call it by yourself. So, just call it in the end of the controller.

这篇关于如何在Web应用程序的单独文件中对Google Maps init进行回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆