带有地理编码功能的谷歌地图
您好,我正在使用谷歌地图 javascript api v3
这是我绘制折线的代码。
for(var i=0; i < addressArr.length; i++){
geocoder.geocode( { 'address': addressArr[i]}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
point = results[0].geometry.location;
place.push(results[0].address_components[1].long_name);
flightPlanCoordinates.push(point);
if(flightPlanCoordinates.length == addressArr.length){
flightPath = new google.maps.Polyline({path: flightPlanCoordinates,strokeColor: "#FF0000",strokeOpacity: 0.50,strokeWeight: 2 });
flightPath.setMap(map);
}
addressArr 是一个地址数组
问题出在我的飞行计划坐标中,它们的顺序与我从 for 循环传递 addressArr 的顺序不同。
假设我传递 addressArr=[1,2,3,4],我的 FlightPlanCoords 变为 [2,3,1,4]。 任何人都可以建议正在发生的事情吗?
Hi I am using google map javascript api v3
here is my code to draw polylines.
for(var i=0; i < addressArr.length; i++){
geocoder.geocode( { 'address': addressArr[i]}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
point = results[0].geometry.location;
place.push(results[0].address_components[1].long_name);
flightPlanCoordinates.push(point);
if(flightPlanCoordinates.length == addressArr.length){
flightPath = new google.maps.Polyline({path: flightPlanCoordinates,strokeColor: "#FF0000",strokeOpacity: 0.50,strokeWeight: 2 });
flightPath.setMap(map);
}
addressArr is an Array of addresses
The problem is in my flightPlanCoordinates ,they are not in the order in which i am passing the addressArr from the for loop.
suppose i am passing addressArr=[1,2,3,4] the my flightPlanCoordinates becomes [2,3,1,4].
Can any suggest what is happening.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这只是因为在循环内部进行异步调用(geocoder.geocode),这需要不同的时间来完成。因此,建议对数组中的第二个元素进行地理编码需要 1 秒,对第一个元素进行地理编码需要 3 秒。那么显然第二个元素的回调函数将在第一个元素之前被调用,从而将其推入第一个位置的飞行计划坐标中。
只需在代码中的第二个 if 语句内对数组调用 sort() 方法即可解决问题。
更新:
That's simply because inside of loop you make asyncronous call(geocoder.geocode) which takes different ammount of time to accomplish. So suggest that it takes 1 second to geocode second element in array and 3 seconds to geocode first element. Then obviously the second element's callback function will be called before the first and thus will push it into flightPlanCoordinates on first position.
Just call sort() method on the array inside of second if statement in your code to solve the issue.
UPDATE:
不太确定为什么它会返回这样的值,但您可以对数组进行排序,这将解决您的问题。飞行计划坐标.sort();
No too sure why its returning the values like that but you could just sort the array and that will resolve your problem. flightPlanCoordinates.sort();