【问题标题】:Google maps saving draggable directions谷歌地图保存可拖动的方向
【发布时间】:2011-06-07 04:04:54
【问题描述】:

您可以在我的网络应用程序中创建标记,并使用这些标记创建带有 google 方向的路线。但我希望用户也能够更改路线,并且我在 google maps api v3 中找到了可拖动的方向。有没有办法将更改的方向保存在数据库中,以便您可以使用该信息再次创建确切的路线?

【问题讨论】:

    标签: javascript api google-maps


    【解决方案1】:

    我将假设以下都是正确的:

    var map = new google.maps.Map(document.getElementById('map_canvas'), {
            zoom: 8,
            center: new google.maps.LatLng(/* center of map */),
            mapTypeId: google.maps.MapTypeId.ROADMAP
        }),
        directions = new google.maps.DirectionsService(),
        displayer = new google.maps.DirectionsRenderer({
            draggable: true
        });
    
    displayer.setMap(map);
    directions.route({
        origin: new google.maps.LatLng(/* start point */),
        destination: new google.maps.LatLng(/* end point */),
        travelMode: google.maps.DirectionsTravelMode.DRIVING
    }, function (result) {
        displayer.setDirections(result);
    });
    

    基本上,这只是假设已经选择了起点和终点,并且已经绘制了默认路线。 (注意:DirectionsRenderer 已被初始化为 draggable: true。)

    当用户更改路由时,应用程序会触发directions_changed 事件。我们可以这样跟踪:

    google.maps.event.addListener(displayer, 'directions_changed', some_method);
    

    在更改路线时会发生其他事情:创建一个新的waypoint。以下是我们如何到达所有航点:

    var some_method = function () {
        var waypoints = displayer.directions.route[0].legs[0].via_waypoint;
    };
    

    变量waypoints 是一个对象数组,描述了路线在前往目的地的途中所经过的站点。 (请注意,已做出更多假设:您使用的是route[0]legs[0] 等)

    每个waypoint 对象都有一个location 属性,其中包含纬度和经度(出于某种原因,分别在location.walocation.ya 中可用)。因此,我们可以告诉应用程序,每次用户更改路线时,旋转(并存储)当前航点的所有纬度和经度。一旦有了这些,您就可以决定如何存储它们(AJAX 到将它们存储在数据库中的服务器端页面,localStorage 等)

    那么!

    下次加载此页面时,您可以从存储中获取这些航点并像这样初始化路线:

    directions.route({
        origin: new google.maps.LatLng(/* start point */),
        destination: new google.maps.LatLng(/* end point */),
        travelMode: google.maps.DirectionsTravelMode.DRIVING,
        waypoints: [
            { location: new google.maps.LatLng(/* lat/lng go here */) } // repeat this as necessary
        ]
    }, function (result) {
        displayer.setDirections(result);
    });
    

    这应该维护用户选择的新路线。最后一点:我在这个答案中遗漏了 很多,比如 他们如何保存它,你如何知道哪个用户想要哪条路线等等。但基础就在那里。神速。

    【讨论】:

    • 优秀的解释和答案。只是一个非常小的/次要更正 - 在 var waypoints = displayer.directions.route[0].legs[0].via_waypoint;它必须是路线而不是路线
    • 如果您将字段stopover: false添加到调用中的每个航点以恢复路线,那么它们将显示为一个可拖动的小圆圈,就像您保存之前一样。
    【解决方案2】:

    这可能在 sdleihssirhc 的回答和现在之间发生了变化,但我尝试了上述解决方案,但它在 displayer.directions.route[0] 上一直失败 说它是未定义的。

    看起来属性已更改为routes,我花了一段时间才弄明白。使用下面的行对我有用:

    var waypoints = displayer.directions.routes[0].legs[0].via_waypoint;
    

    希望这将为任何试图让它发挥作用的人节省一些时间和挫败感。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-09-17
      • 1970-01-01
      • 2011-08-07
      • 2016-08-30
      • 1970-01-01
      • 2011-11-18
      • 1970-01-01
      • 2018-04-11
      相关资源
      最近更新 更多