javascript - Google Maps: geocode addresses asynchronously, but get their responses in order - Stack Overflow

I'm trying to plot lines between two or more addresses in Google Maps. The idea is that addresses

I'm trying to plot lines between two or more addresses in Google Maps. The idea is that addresses are in an array (in the order of the route taken), then the array is looped over and geocoded via Google Maps, so I then have an array of co-ordinates:

function showRoute(routes) {
    var points = [];
    var geocoder = new GClientGeocoder();
    for (var i = 0; i < routes.length; i++) {
        geocoder.getLatLng(routes[i], function(point) {
            points.push(point);
            drawRoute(points, routes);
        });
    }
}

The drawRoute() function will only run through if the array passed to it is the same as the length of the original routes array.

Most of the time this works fine. However, it will break if there's a lag in getting a response from the geocoder for any value, as it'll result in them being out of order.

My first attempt around this problem was as follows:

function showRoute(routes) {
    var points = [];
    var geocoder = new GClientGeocoder();
    for (var i = 0; i < routes.length; i++) {
        geocoder.getLatLng(routes[i], function(point) {
            points[i] = point;
            drawRoute(points, routes);
        });
    }
}

But as the function runs asynchronously, it means that the value of i inside the geocode callback is always going to be the length of the routes array, so it'll just keep overwriting the same value.

Anyone got any ideas?

I'm trying to plot lines between two or more addresses in Google Maps. The idea is that addresses are in an array (in the order of the route taken), then the array is looped over and geocoded via Google Maps, so I then have an array of co-ordinates:

function showRoute(routes) {
    var points = [];
    var geocoder = new GClientGeocoder();
    for (var i = 0; i < routes.length; i++) {
        geocoder.getLatLng(routes[i], function(point) {
            points.push(point);
            drawRoute(points, routes);
        });
    }
}

The drawRoute() function will only run through if the array passed to it is the same as the length of the original routes array.

Most of the time this works fine. However, it will break if there's a lag in getting a response from the geocoder for any value, as it'll result in them being out of order.

My first attempt around this problem was as follows:

function showRoute(routes) {
    var points = [];
    var geocoder = new GClientGeocoder();
    for (var i = 0; i < routes.length; i++) {
        geocoder.getLatLng(routes[i], function(point) {
            points[i] = point;
            drawRoute(points, routes);
        });
    }
}

But as the function runs asynchronously, it means that the value of i inside the geocode callback is always going to be the length of the routes array, so it'll just keep overwriting the same value.

Anyone got any ideas?

Share Improve this question asked Nov 19, 2009 at 23:48 David MDavid M 352 silver badges6 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 4

Ok. So I had to do a search on SO and re-read how closures work before I answered this question (seems like I always have to do that when ever I think about closures).

The value of the index variable is set when the outer function returns (that is showRoute in this case). So I figured, all you need to do is wrap up your getLatLng in another function that takes the index as a parameter:

function processPoint (geocoder, routes, i, points)
{
    geocoder.getLatLng(routes[i], function(point) {
        points[i] = point;
        drawRoute (points, routes);
        });
}

So your loop in showRoute bees:

var geocoder = new GClientGeocoder();
for (var i = 0; i < wp.length; i++) 
     processPoint (geocoder, routes, i, points);

This way the getLatLng callback has access to the appropriate index value. I did a quick example which demonstrates this working. You can find the source for this here.

You want to do each geocode one at a time, and have the callback invoke the next geocode. This will guarantee the ordering.

E.g.:

var map = null;
var geocoder = null;
var next = 0;
var points = [];

var addresses = [
  "1521 1st Ave, Seattle, WA",
  "2222 2nd Ave, Seattle, WA",
  "14 Mercer St, Seattle, WA"
];

function initialize() {
  if (GBrowserIsCompatible()) {
    map = new GMap2(document.getElementById("map_canvas"));
    map.setCenter(new GLatLng(47.61630, -122.34546), 13);
    map.setUIToDefault();
    geocoder = new GClientGeocoder();
    geocodeAll();
  }
}

function geocodeAll() {
  if (next < addresses.length) {
    // Do the next one.
    geocoder.getLatLng(addresses[next], callBack);
  } else {
    doneCb();  // All done.
  }
  next += 1;
}

function callBack(point) {
  points.push(point);
  geocodeAll();
}

// Called when all done.
function doneCb() {
  // Add a polyline connecting the dots.
  var poly = new GPolyline(points);
  map.addOverlay(poly);

  // Add some markers over the points.
  for (var i = 0; i < points.length; ++i) {
    map.addOverlay(new GMarker(points[i]));
  }
}

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745643127a4637812.html

相关推荐

  • PackML over OPC UA

    在当今数字化转型的浪潮中,制造业正面临着前所未有的挑战与机遇。如何实现设备之间的高效通信与集成,成为提升生产效率、降低成本的关键。OPC UA(OPC Unified Architecture)与PackML(Packaging Machi

    1小时前
    00
  • 1.8w字图解Java并发容器: CHM、ConcurrentLinkedQueue、7 种阻塞队列的使用场景和原理

    文章多图且内容硬核,建议大家收藏上一章《1.6w 字图解 Java 并发:多线程挑战、线程状态和通信、死锁;AQS、ReentrantLock、Condition 使用和原理》,我们开启了 Java 高并发系列的学习,透彻理解 Java 并

    1小时前
    00
  • 初始JESD204B高速接口协议(JESD204B一)

    01、对比LVDS与JESD204JESD204B是逻辑器件和高速ADCDAC通信的一个串行接口协议,在此之前,ADCDAC与逻辑器件交互的接口大致分为如下几种。低速串行接口(I2C、SPI)、低速并行接口(包含时钟信号和并行数据信号,

    1小时前
    00
  • 我用AI监控了奥特曼,当他一发推特AI就会自动给我打电话。

    上周我真的扛不住了。奥特曼这个孙贼,发了个X说,“要发一个礼拜的好东西”。我信了他的邪,明明出差1周,每天早上9点不到就要起来参加活动,但是晚上根本不敢睡觉,天天蹲到凌晨3点半,蹲到他们那边时间中午12点多,我才敢去睡觉。真的,那一整周,我

    1小时前
    00
  • 长读长测序揭示结直肠癌异常可变剪接图谱与新型治疗靶点

    徐州医科大学肿瘤研究所董东郑骏年教授团队在Genome Medicine杂志发表题为“Long-read sequencing reveals the landscape of aberrant alternative splicing

    49分钟前
    00
  • MongoDB “升级项目” 大型连续剧(2)

    上期写的是非必要不升级,想到这个事情,有一些事情的仔细琢磨琢磨,为什么数据库升级的事情在很多公司都是一个困扰,从一个技术人的观点,升级是一件好事,功能提升了,性能提升了,开发效率和一些数据库使用的痛点也被解决了,为什么就不愿意升级呢?如果只

    33分钟前
    00
  • 深度学习在DOM解析中的应用:自动识别页面关键内容区块

    爬虫代理摘要本文介绍了如何在爬取东方财富吧()财经新闻时,利用深度学习模型对 DOM 树中的内容区块进行自动识别和过滤,并将新闻标题、时间、正文等关键信息分类存储。文章聚焦爬虫整体性能瓶颈,通过指标对比、优化策略、压测数据及改进结果,展示了

    30分钟前
    10
  • 什么是docker?它是如何工作的?

    想象一个场景,你要部署一个服务,然后它对环境有很多依赖,不同的操作系统又是不同的需求,而且还可能遇到有些源不能使用,又得一番折腾,折腾完上线后,假设要在新的环境再来一套,又得再来一遍。那么有没有什么办法可以解决呢?有办法,docker就是干

    28分钟前
    00
  • UCB的硅光MEMS OCS控制技术

    昨天写的旭创与nEye合作了一个64端口硅光OCS一、光电路交换技术概述(一)电交换与分组交换电路交换的概念源于早期的电话交换机,通过物理连接实现设备间的通信,就像早期打电话时,接线员手动连接线路一样。而分组交换则是

    27分钟前
    00
  • 【Docker项目实战】使用Docker部署IT工具箱Team·IDE

    一、Team·IDE介绍1.1 Team·IDE简介Team IDE 是一款集成多种数据库(如 MySQL、Oracle、金仓、达梦、神通等)与分布式系统组件(如 Redis、Zookeeper、Kafka、Elasticsearch)管理

    22分钟前
    00
  • 大模型驱动金融数据应用的实战探索

    近年来,人工智能技术的飞速发展正在重塑全球各行各业的生态格局,金融行业作为数据密集型领域,更是首当其冲。大模型凭借其强大的自然语言处理、逻辑推理和生成能力,逐渐成为金融数据应用的核心驱动力。本文将从行业背景与趋势、核心场景重构、产品能力提升

    21分钟前
    00
  • 人工智能与ai有什么区别

    一、引言:概念之辨的必要性在科技浪潮席卷全球的当下,人工智能(Artificial Intelligence,简称AI)已成为人们耳熟能详的词汇。然而,当我们深入探讨时,会发现“人工智能”与“AI”这两个表述在语义和使用场景上存在微妙差异。

    16分钟前
    00
  • 在VMware虚拟机中安装Windows 7全攻略(避坑指南)

    ⚠️写在前面 最近发现很多开发者在调试老旧系统时都需要用到Windows 7环境&#xff08;特别是银行、医疗等行业的遗留系统&#xff09;&#xff0c;但实体机安装既不现实也不安全。今天就手把手教你在虚拟机

    14分钟前
    00
  • 雨晨 22635.5170 Windows 11 企业版 23H2 轻装版

    文件: 雨晨 22635.5170 Windows 11 企业版 23H2 轻装版 install.esd 大小: 2920270404 字节 修改时间: 2025年4月8日, 星期二, 11 : 04 : 59 MD5: D5F8F0AD

    11分钟前
    00
  • Windows系统密钥检测工具PIDKey 2.1中文版

    Windows系统密钥检测工具PIDKey 2.1中文版 【下载地址】Windows系统密钥检测工具PIDKey2.1中文版 Windows系统密钥检测工具PIDKey 2.1中文版是一款功能强大的工具&#xff0c;专为管理Win

    9分钟前
    00
  • 雨晨 26200.5516 Windows 11 IoT 企业版 LTSC 2024 轻装版

    简述&#xff1a;以下为YCDISM (雨晨作品自2025年03月25日起通用介绍&#xff0c;若无重大更改不再额外敖述) 全程由最新YCDISM2025脱机装载26100.1742_zh-cn_windows_11_

    6分钟前
    00
  • ​2025 轻松部署 Odoo 18 社区版

    随着 Odoo 18 社区版的发布,越来越多的企业希望借助这款开源 ERP 系统实现数字化转型。本文将深入解析传统部署方式的底层逻辑,并揭示如何通过自动化工具实现零门槛快速部署。一、手工部署 Odoo 18 技术全解 Docker 环境搭建

    5分钟前
    00
  • Java&amp;Activiti7实战:轻松构建你的第一个工作流

    本文已收录在Github,关注我,紧跟本系列专栏文章,咱们下篇再续!

    3分钟前
    00
  • 用Xshell8配置密钥登陆

    1.首先在服务端查看root.sshauthorized_keys是否存在,这是存储公钥的文件,若不存在需新建此文件 2. 打开Xshell8,选择"新建",选择"新建用户密钥生成向导" 给用户

    2分钟前
    00
  • windows切换系统版本

    powershell 管理员身份打开 输入 irm massgrave.devget | iex 输入数字 对应后面写着 change windows edition新的会话框中选择想要的版本即可 获取windows 密钥 官方提供的

    18秒前
    00

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信