使用 Google Maps API 绘制地图路径/航点并播放路线

2024-01-19

我试图在播放映射路线时绘制访问的路径,如下例所示:

加载地图时,我希望绘制的点 A、B、C、D、E,然后 F 依次连接。

我已成功绘制了这些点,但无法将这些点逐个动态链接。

这是我的代码:

<script type="text/javascript">
var markers = [{
    "title": 'Alibaug',
    "lat": '12.97721863',
    "lng": '80.22206879',
    "description": 'Alibaug is a coastal town and a municipal council in Raigad District in the Konkan region of Maharashtra, India.'
}, {
    "title": 'Mumbai',
    "lat": '12.9962529',
    "lng": '80.2570098',
    "description": 'Mumbai formerly Bombay, is the capital city of the Indian state of Maharashtra.'
}, {
    "title": 'Pune',
    "lat": '12.97722816',
    "lng": '80.22219086',
    "description": 'Pune is the seventh largest metropolis in India, the second largest in the state of Maharashtra after Mumbai.'
}];
window.onload = function() {
    var mapOptions = {
        center: new google.maps.LatLng(markers[0].lat, markers[0].lng),
        zoom: 10,
        mapTypeId: google.maps.MapTypeId.ROADMAP,};
    var map = new google.maps.Map(document.getElementById("dvMap"), mapOptions);

    //*********** GOOGLE MAP SEARCH ****************//
    // Create the search box and link it to the UI element.
    var input = /** @type {HTMLInputElement} */ (
        document.getElementById('pac-input'));
    map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);

    var searchBox = new google.maps.places.SearchBox(
        /** @type {HTMLInputElement} */
        (input));
    // Listen for the event fired when the user selects an item from the
    // pick list. Retrieve the matching places for that item.
    google.maps.event.addListener(searchBox, 'places_changed', function() {
        var places = searchBox.getPlaces();

        for (var i = 0, marker; marker = markers[i]; i++) {
            // marker.setMap(null);
        }

        // For each place, get the icon, place name, and location.
        markers = [];
        var bounds = new google.maps.LatLngBounds();
        var place = null;
        var viewport = null;
        for (var i = 0; place = places[i]; i++) {
            var image = {
                url: place.icon,
                size: new google.maps.Size(71, 71),
                origin: new google.maps.Point(0, 0),
                anchor: new google.maps.Point(17, 34),
                scaledSize: new google.maps.Size(25, 25)
            };

            // Create a marker for each place.
            var marker = new google.maps.Marker({
                map: map,
                icon: image,
                title: place.name,
                position: place.geometry.location
            });
            viewport = place.geometry.viewport;
            markers.push(marker);

            bounds.extend(place.geometry.location);
        }
        map.setCenter(bounds.getCenter());
    });
    // Bias the SearchBox results towards places that are within the bounds of the
    // current map's viewport.
    google.maps.event.addListener(map, 'bounds_changed', function() {
        var bounds = map.getBounds();
        searchBox.setBounds(bounds);
    });
    //***********Google Map Search Ends****************//


    var infoWindow = new google.maps.InfoWindow();
    var lat_lng = new Array();
    var latlngbounds = new google.maps.LatLngBounds();
    for (i = 0; i < markers.length; i++) {
        var data = markers[i]
        var myLatlng = new google.maps.LatLng(data.lat, data.lng);
        lat_lng.push(myLatlng);
        var marker = new google.maps.Marker({
            position: myLatlng,
            map: map,
            title: data.title
        });
        latlngbounds.extend(marker.position);
        (function(marker, data) {
            google.maps.event.addListener(marker, "click", function(e) {
                infoWindow.setContent(data.description);
                infoWindow.open(map, marker);
            });
        })(marker, data);
    }
    map.setCenter(latlngbounds.getCenter());
    map.fitBounds(latlngbounds);

    //***********ROUTING****************//

    //Initialize the Path Array
    var path = new google.maps.MVCArray();

    //Initialize the Direction Service
    var service = new google.maps.DirectionsService();

    //Set the Path Stroke Color
    var poly = new google.maps.Polyline({
        map: map,
        strokeColor: '#4986E7'
    });

    //Loop and Draw Path Route between the Points on MAP
    for (var i = 0; i < lat_lng.length; i++) {
        if ((i + 1) < lat_lng.length) {
            var src = lat_lng[i];
            var des = lat_lng[i + 1];
            path.push(src);
            poly.setPath(path);
            service.route({
                origin: src,
                destination: des,
                travelMode: google.maps.DirectionsTravelMode.DRIVING
            }, function(result, status) {
                if (status == google.maps.DirectionsStatus.OK) {
                    for (var i = 0, len = result.routes[0].overview_path.length; i < len; i++) {
                        path.push(result.routes[0].overview_path[i]);
                    }
                }
            });
        }
    }
}

function handleLocationError(browserHasGeolocation, infoWindow, pos) {
    infoWindow.setPosition(pos);
    infoWindow.setContent(browserHasGeolocation ?
        'Error: The Geolocation service failed.' :
        'Error: Your browser doesn\'t support geolocation.');
}

Output will be similar to: Google map showing points along a route

如何回放显示该映射路线沿线的点?有工作示例吗?


有一篇很好的博客文章,其中包含示例代码,位于https://duncan99.wordpress.com/2015/01/22/animated-paths-with-google-maps/ https://duncan99.wordpress.com/2015/01/22/animated-paths-with-google-maps/解释如何为路线设置动画。

该示例与您的问题之间的区别在于您的路线中有航路点。您可以使用航路点立即获取整个路线,也可以像上面的代码中那样获取路线。我在下面包含了一个使用航路点的编码片段(免费版本的谷歌地图最多可提供 8 个航路点)。如果您在代码中使用该方法,则需要确保在开始动画之前已加载整个路径。

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>Map Example</title>
</head>

<body>
  <button id="animate">Redo Animation</button>
  <div id="map_canvas" style="width: 600px;height: 600px"></div>
  <script type="text/javascript">
    var markers = [{
      "title": 'Alibaug',
      "lat": '18.6581725',
      "lng": '72.8637616',
      "description": 'Alibaug is a coastal town and a municipal council in Raigad District in the Konkan region of Maharashtra, India.'
    }, {
      "title": 'Mumbai',
      "lat": '19.0458547',
      "lng": '72.9434202',
      "description": 'Mumbai formerly Bombay, is the capital city of the Indian state of Maharashtra.'
    }, {
      "title": 'Pune',
      "lat": '18.5247663',
      "lng": '73.7929273',
      "description": 'Pune is the seventh largest metropolis in India, the second largest in the state of Maharashtra after Mumbai.'
    }];

    function animatePath(map, route, marker, pathCoords) {
      var index = 0;
      route.setPath([]);
      for (var index = 0; index < pathCoords.length; index++)
        setTimeout(function(offset) {
          route.getPath().push(pathCoords.getAt(offset));
          marker.setPosition(pathCoords.getAt(offset));
          map.panTo(pathCoords.getAt(offset));
        }, index * 30, index);
    }

    function initialize() {

      var mapOptions = {
        center: new google.maps.LatLng(markers[0].lat, markers[0].lng),
        zoom: 20,
        mapTypeId: google.maps.MapTypeId.ROADMAP
      };

      var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);

      var infoWindow = new google.maps.InfoWindow();
      var latlngbounds = new google.maps.LatLngBounds();
      for (i = 0; i < markers.length; i++) {
        var data = markers[i];
        markers[i].latLng = new google.maps.LatLng(data.lat, data.lng);
        var marker = new google.maps.Marker({
          position: markers[i].latLng,
          map: map,
          title: data.title
        });
        marker.description = markers[i].description;
        latlngbounds.extend(marker.position);
        google.maps.event.addListener(marker, "click", function(e) {
          infoWindow.setContent(this.description);
          infoWindow.open(map, this);
        });
      }
      map.setCenter(latlngbounds.getCenter());
      map.fitBounds(latlngbounds);

      //Initialize the Path Array
      var path = new google.maps.MVCArray();

      //Initialize the Direction Service
      var service = new google.maps.DirectionsService();

      // Get the route between the points on the map
      var wayPoints = [];
      for (var i = 1; i < markers.length - 1; i++) {
        wayPoints.push({
          location: markers[i].latLng,
          stopover: false
        });
      }
      //Initialize the path
      var poly = new google.maps.Polyline({
        map: map,
        strokeColor: '#4986E7'
      });
      var traceMarker = new google.maps.Marker({
        map: map,
        icon: "http://maps.google.com/mapfiles/ms/micons/blue.png"
      });

      if (markers.length >= 2) {
        service.route({
          origin: markers[0].latLng,
          destination: markers[markers.length - 1].latLng,
          waypoints: wayPoints,
          travelMode: google.maps.DirectionsTravelMode.DRIVING
        }, function(result, status) {
          if (status == google.maps.DirectionsStatus.OK) {
            for (var j = 0, len = result.routes[0].overview_path.length; j < len; j++) {
              path.push(result.routes[0].overview_path[j]);
            }
            animatePath(map, poly, traceMarker, path);
          }
        });
      }

      document.getElementById("animate").addEventListener("click", function() {
        // Animate the path when the button is clicked
        animatePath(map, poly, traceMarker, path);
      });

    };
  </script>
    <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&callback=initialize"></script>
</body>

</html>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 Google Maps API 绘制地图路径/航点并播放路线 的相关文章

随机推荐

  • 扩展 MVC3 razor Html.LabelFor 添加 css 类

    我正在尝试将 css 类添加到 EditorTemplate 上的 Html LabelFor Html LabelFor model gt model Name new class myLabel 我的期望例如 label 应该选择 cs
  • BigQuery 写入时数据流作业失败并出现后端错误

    我的工作因最终导入 BigQuery 相关的几个不同错误而失败 我已经运行了 5 次 每次都失败 尽管错误消息有时会有所不同 当我在本地针对 SQLite 数据库运行该工作时 该工作运行良好 因此我认为问题出在 Google 后端 一条错误
  • 使用 SSL 的 wcf net.tcp

    有人有在 WCF 中使用 SSL 和 net tcp 绑定的经验吗 我读过这是可能的 但没有找到有关如何实现它的良好信息 我很想听听任何了解或实施过这一点的人的意见 提前致谢 看看这个链接里的内容 http msdn microsoft c
  • 通过传递带有要选择的列名称的有序向量,对 dplyr 中的列进行动态排序

    我使用下面的代码生成一个简单的汇总表 Data data mtcars Lib require dplyr Summary mt sum lt mtcars gt group by am gt summarise each funs min
  • php 回显尖括号

    我想在页面上显示文本 文本应该如下所示
  • CASE 语句未正确定义列雪花

    我有一个以下格式的查询 用于执行COALESCE以及使用定义一个新列CASE陈述 SELECT COALESCE mm1 missing AS mm1 COALESCE mm2 missing AS mm2 CASE WHEN mm1 fa
  • HTML::PullParser 随机分割文本元素

    我正在使用 Perl 模块HTML PullParser 我注意到它有时会随机分割文本元素 据我所知 例如 如果我有一个 html 文件test html与内容 font style font family none size 2 THE
  • 确定掷骰子中数字出现的频率

    对于游戏 我试图确定在给定的骰子数量下特定的 出现的频率 我知道 这个问题看起来很奇怪 让我尝试用实际数字来解释它 因此 对于 1 个骰子 每个数字的频率将相同 1 6 将出现相同的次数 现在对于 2 个骰子 情况会变得不同 我想 5 6
  • 无法为 Facebook 测试用户添加当前城市

    我正在开发基于位置的功能 因此在测试应用程序下创建了一些 Facebook 测试帐户 我试图为所有测试用户添加当前城市 手动 但 Facebook 在输入城市时抛出以下错误 您请求的内容现在无法显示 可能是 暂时不可用 您点击的链接可能已过
  • Linux 下的 Ruby 不区分大小写地打开文件

    有没有办法在Linux下的Ruby中不区分大小写地打开文件 例如 给定字符串foo txt 我可以打开该文件吗FOO txt 一种可能的方法是读取目录中的所有文件名并手动搜索所需文件的列表 但我正在寻找一种更直接的方法 一种方法是编写一个小
  • 将 EAR 模块转为 OSGI 包的正确方法

    有必要将 EAR 的一部分 即战争 转变成 OSGI 包并保留其互操作性 Glassfish 3 0 1 已经有了osgi web container模块 我成功部署了独立的 OSGI war 但如果是前企业战争 我觉得有点困难 我该如何处
  • solr 地理层次结构

    我一直在试图找出一种在 solr 中实现层次结构分面的方法 但不知道在我的情况下如何做到这一点 我读过几篇关于在 solr 中进行层次结构的文章以及补丁 64 和 792 中的解决方案 我遇到的主要问题是我的实体可以属于层次结构的多个分支
  • R ggplot2 - 简单绘图 - 无法指定对数轴限制

    我正在尝试在 R 中的 ggplot2 中创建一个简单的密度图 这是我的代码 效果很好 d lt ggplot result aes x result baseMeanA d geom density colour darkgreen si
  • 如何将 java.time.Instant 格式化为本地时区的字符串?

    如何格式化javax time Instant http threeten sourceforge net apidocs 2011 01 07 javax time Instant html作为本地时区的字符串 以下是本地翻译的Insta
  • RadDateTimePicker + 用于数据输入的掩码

    要求 允许用户以 格式输入日期 同时还可以从 DatePicker 中选择日期 假设输入的所有年份都是 2000 年之后 例如 用户输入 050513 它会变成 5 5 2013年 或者 如果他们从 DatePicker 中选择它 则提供相
  • Scalatest 和 Spark 给出“java.io.NotSerializedException:org.scalatest.Assertions$AssertionsHelper”

    我正在借助 测试 Spark Streaming 应用程序com holdenkarau spark 测试基地 and 分级测试 import com holdenkarau spark testing StreamingSuiteBase
  • Rails 包含范围

    我有一个名为 Author 的模型 一个作者有很多文章 文章有一个名为 published 的范围 它的作用是 where published true 我想加载作者以及已发表的文章 我试过 Author includes articles
  • Pandas 的部分总和和小计

    I m trying to achieve a table with subtotals as shown here http pandas pydata org pandas docs stable cookbook html pivot
  • pandas 行值到列标题

    我有一个像这样的数据框 df pd DataFrame id1 1 1 1 1 2 2 2 id2 1 1 1 1 2 2 2 value a b c d a b c id1 id2 value 0 1 1 a 1 1 1 b 2 1 1
  • 使用 Google Maps API 绘制地图路径/航点并播放路线

    我试图在播放映射路线时绘制访问的路径 如下例所示 加载地图时 我希望绘制的点 A B C D E 然后 F 依次连接 我已成功绘制了这些点 但无法将这些点逐个动态链接 这是我的代码