Google Maps API:设置回调以添加标记/多段线 [英] Google Maps API: Setting up callbacks for adding markers/polyline

查看:132
本文介绍了Google Maps API:设置回调以添加标记/多段线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为生成的Google地图添加折线。多段线的坐标是使用jQuery(getJSON函数)从我的Web服务器上的JSON文件中获取的。但是,我遇到回调问题。我在一个单独的JavaScript文件中定义了三个函数,它们是:
$ b $ pre $函数initMap(callback){

map = new google.maps.Map(document.getElementById('map-canvas'),{
center:{lat:34.397,lng:150.644},
scrollwheel:false,
zoom:2
});

callback();
}

 function setPath(callback){

$ .getJSON('./ expOneActivityData.json',

function(data){

//一些循环的contstruct来浏览我的JSON文件
}
})

callback();
};

  function addPath(){

var trekLine = new google.maps.Polyline({

path:expeditionCoordinates,
geodisc:true,
stokeColor:'#FF0000',
strokeOpacity:1.0,
strokeWeight:2
});

trekLine.setMap(map);






expeditionCoordinates是一个数组,每个元素都是一个纬度对象和经度属性。这被声明为一个全局变量,其值初始化发生在setPath()的循环中。



在我的HTML文件中,我有:

 < script src =https://maps.googleapis.com/maps/api/js?key=myKey&callback=initMap> 



当我尝试替换initMap在脚本标记中使用initMap(setPath(addPath))时,我收到了来自Google的400次错误请求。在脚本标签中只有callback = initMap的情况下给出:

  TypeError:回调不是函数

出现在initMap定义的callback()行中。

那么我怎样才能将函数传递给googleapis,函数本身也有回调函数? (我的循环构造很好btw)。我试着向googleapi脚本标记添加'延迟',并且还添加了链接到我的JavaScript文件的链接。我删除了所有回调的东西,只执行循环。我希望expeditionCoordinates数组能够在googleapi脚本标记被执行之前完成初始化,尽管这也没有效果(map仍然会加载,只是没有多段线)。



我是相当新的Javascript和它是异步的性质,但我明白他们是如何工作的,并在一周左右的时间里与他们在基本水平上成功地合作。



实际上我引起了一个侧面的问题,到现在为止,我只用过一次回调,我希望看到类似于:

initMap(setPath)

作为setPath工作时没有()附加,当它的定义作为因为它也需要一个回调函数(addPath),这意味着它会马上执行)

解决方案

提供的例子有几个问题:

1)在Google Maps API中, callback 参数接受
callback 函数名称,函数本身应该具有
签名:

 函数initMap(){
// ...
}

其中

 <脚本src =https://maps.googleapis.com/maps/api/js?key=myKey&callback=initMapasync defer>< / script> 




只能使用这种方式指定无参数回调函数。


2)由于 jQuery.getJSON() 默认情况下是 async ,并传递函数callback,执行< code $> setPath 函数应该是这样的: $ b $ .getJSON('./ expOneActivityData.json',
function(data){
callback(data);
}
);
};

工作示例

 

<身高:100%;保证金:0; padding:0;}#map-canvas {height:100%;}

 < script src =https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js>< / script>< div id =map -canvas>< / div>< script src =https://maps.googleapis.com/maps/api/js?libraries=places&callback=initMapasync defer>< / script>  


I'm trying to add a polyline to the Google Map generated. The coordinates for the polyline are taken from a JSON file on my web server using jQuery (getJSON function). However, I'm having trouble with callbacks. I've defined three functions in a separate JavaScript file, and these are:

function initMap(callback) {

    map = new google.maps.Map(document.getElementById('map-canvas'), {
        center: {lat: 34.397, lng: 150.644},
        scrollwheel: false,
        zoom: 2
    });

    callback();
}

.

function setPath(callback) {

   $.getJSON('./expOneActivityData.json',

       function (data) {

           //Some looping contstruct to navigate through my JSON file.   
       }
   })

   callback();
};

.

function addPath() {

    var trekLine = new google.maps.Polyline({

        path: expeditionCoordinates,
        geodisc: true,
        stokeColor: '#FF0000',
        strokeOpacity: 1.0,
        strokeWeight: 2
    });

    trekLine.setMap(map);

}

expeditionCoordinates being an array, each element being an object with latitude and longitude property. This is declared as a global variable, with value initialisation happening in setPath()'s loop.

In my HTML file, I have:

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

When I try to replace initMap with initMap(setPath(addPath)) in the script tag, I get a 400 Bad request from Google. Ofcourse having just "callback=initMap" in the script tag gives a:

TypeError: callback is not a function

occuring at line with callback() in initMap's definition.

So how can I pass a function to googleapis, where the function itself also has callbacks? (My looping construct is fine btw). I tried adding 'defer' to the googleapi script tag, and also to the one linking to my JavaScript file. I removed all the callbacks stuff, and only excecuted the loop. I hoped the expeditionCoordinates array would finish initialisation before the googleapi script tag is excecuted, though that didnt work either (map still loads, just with no polyline).

I'm fairly new to Javascript and it's asynchronous nature, though I do understand how they work and have been succesfully working with them at a basic level for a week or so.

(Which actually leads me to a side question. Up until now I've only worked with one callback. I would expect something like:

initMap(setPath)

to work as setPath does not have () attached when its definition is passed as a parameter, and hence is not excecuting immediately. Though adding a set of brackets to setPath, as it also takes a callback (addPath), would mean it does get excecuted immediately?)

解决方案

There are several issues with the provided example:

1) When loading the Google Maps API, callback parameter accepts callback function name where the function itself should have the following signature:

function initMap() {
   //...
}

where

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

Only parameter-less callback function could be specified this way.

2) Since jQuery.getJSON() is async by default and you are passing function callback, the implementation of setPath function should like this:

function setPath(callback) {
    $.getJSON('./expOneActivityData.json',
        function (data) {
            callback(data);
        }
    );
};

Working example

function initMap() {
    var map = new google.maps.Map(document.getElementById('map-canvas'), {
        center: { lat: 34.397, lng: 150.644 },
        scrollwheel: false,
        zoom: 2
    });

    setPath(function(data) {
        addPath(map,data);
    });
}

function setPath(callback) {
    $.getJSON('https://gist.githubusercontent.com/vgrem/91ba4d694157169b112c/raw/5bdd81c6f5bdfa5ba2d0ca8d5494129b329399d8/expOneActivityData.json',
        function (data) {
            callback(data);
        }
    );
};


function addPath(map,expeditionCoordinates) {
    var trekLine = new google.maps.Polyline({
        path: expeditionCoordinates,
        geodisc: true,
        stokeColor: '#FF0000',
        strokeOpacity: 1.0,
        strokeWeight: 2
    });
    trekLine.setMap(map);
}

html, body {
    height: 100%;
    margin: 0;
    padding: 0;
}

#map-canvas {
    height: 100%;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<div id="map-canvas"></div>
<script src="https://maps.googleapis.com/maps/api/js?libraries=places&callback=initMap"
            async defer></script>

这篇关于Google Maps API:设置回调以添加标记/多段线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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