我有一个socket.io,它每15到20毫秒ping一个新地址。对于此地址,我必须获取经纬度并将标记放置在Google地图中。因此,在那15-20毫秒内(如果不是,可能在50-60毫秒内),我必须获取GeoLocation。目前,我正在使用geocoder = new google.maps.Geocoder();
,然后使用geocoder.geocode({address: data}, myFunction(){});
但是此Maps API非常慢。它在400-500毫秒内返回GeoLocation,这使我的中间地址请求为空。我需要一个非常快的API。
作为参考,以下是socket.io的代码段:
geocoder = new google.maps.Geocoder();
var socket = io.connect('http://localhost');
socket.on('new_address', function (data) {
//Gets called everytime a new request for GeoLocation comes
geocoder.geocode({address: data}, placeMarker);
});
var placeMarker = function(){
//Add Marker to GoogleMaps
};
最佳答案
正如评论中提到的那样,您实际上不能期望互联网上20毫秒内有响应,但是那样行不通。但是,您要做的就是使用地址建立某种池,然后让地址解析器(或4之3)按照自己的速度对其进行处理。
这可能看起来像这样(只是在这里给出一个方向,不要指望它立即起作用):
var addresses = [];
var socket = io.connect('http://localhost');
socket.on('new_address', function (data) {
//Gets called everytime a new request for GeoLocation comes
//Adds an address to the list when it comes in from the backend
adresses.push(data);
});
var geocoder = new google.maps.Geocoder();
//This function is called in a loop.
var addressCheck = function() {
//When the list of addresses is empty, because we haven't received anything from the backend, just wait for a bit and call this function again.
if(addresses.length == 0) {
setTimeout(addressCheck, 400);
return;
}
//Get the first one on the list.
var data = addresses[0];
//Process it.
geocoder.geocode({address: data}, function() {
placeMarker();
//remove the first element from the adresses list.
addresses.shift();
//Call the entire function again, so it starts with a new address.
addressCheck();
});
}
var placeMarker = function(){
//Add Marker to GoogleMaps
};
addressCheck();