从谷歌地图中获取拖曳路线数据

8
我正在进行一个项目,目前遇到了无法继续的困境,需要一些严肃的帮助。让我给你一些背景。
我正在开发一个服务,可以让骑自行车前往同一目的地的用户从多个起点协调他们的骑行。我们设计的工作流程之一是让用户使用Google Maps服务构建地图;他们输入起始目的地,Google会创建一条它认为可行的路线,然后用户可以通过拖动点来满足他们特定的需求来调整该路线。我们已经开发了这个界面,并且在以下网址上运行良好:

http://ridestreaming.com/google_maps/

我遇到了一个无法逾越的障碍,就是如何将用户编辑的路线从Google Maps中取出并保存在数据库中供将来参考。似乎我们在Javascript中有一种方法可以做到这一点,在这个文件中(344-352行):

http://ridestreaming.com/google_maps/workflow.js

    var newString = JSON.stringify(directions);
    //set up area to place drop directionsResponse object string
    var directions_response_panel = document.getElementById("directions_response");
    //dump any contents in directions_response_panel
    directions_response_panel.innerHTML = "";
    //add JSON string to it 
    directions_response_panel.innerHTML = "<pre>" + newString + "</pre>";
    //run the ajax
    runAjax(directions);

我们可以将路线数据作为JSON文件提取出来,对其进行字符串化,并通过AJAX发送到一个PHP文件中,我们打算在其中处理并将其存储在MySQL中。然而,从Google Maps返回的JSON似乎格式不正确; 当PHP尝试解码它时,它会出现错误,并且我通过在线验证器运行它以确认其格式不正确。此时,我们完全困惑,不知道如何继续前进。
有没有可能有人能够协助处理这个问题?我已经到了撞墙的地步。非常感谢您的时间!

1
你的注释写着“//重要!这是Directions JSON对象”,但是Google Maps API for DirectionsResults指出:“请注意,尽管此结果类似于JSON,但它并不严格符合JSON规范,因为它间接包含LatLng对象。”这可能是你收到格式错误的JSON的原因吗? - Crag
完全有可能。我不知道关于DirectionsResults对象的这个。有没有一种方法来解析这个格式不正确的JSON? - mcleodm3
你可以看一下这个网址:http://www.devshed.com/c/a/PHP/Parsing-Google-Maps-API-using-PHP-and-JSON-2348127/。我只在javascript中使用过DirectionsResults,从未使用过JSON,所以除此之外我无法提供更多帮助。 - Crag
3个回答

2

我一直在做类似的事情,发现这真的很困难。但是经过几个小时的努力,我成功地从用户拖动的路线中获取了所有航点,并将其保存到数据库中。

因此,我有一个字段,其中包含由“;”分隔的所有航点。

你必须要有这个:

directionsDisplay = new google.maps.DirectionsRenderer({
    'map': map,
    'preserveViewport': true,
    'draggable': true
});

在您的初始化函数中

这是我的JS一部分:

var currentDirections;
var directionsDisplay;
var waypoints = [];
    function saveWaypoints()
    {
        waypoints = [];
        var waypts_field = document.getElementById('waypoints').value.split(';');
        for(var bo = 0; bo < waypts_field.length; bo++)
        {
            if(waypts_field[bo] == ' ' || waypts_field[bo] == '')
            {
                waypts_field.splice(bo,1);
                bo -= 1;
                continue;
            }

            waypoints.push({ location: waypts_field[bo], stopover: false });
        }
    }


    function getWaypoints()
{
    currentDirections = directionsDisplay.getDirections();
    var route = currentDirections.routes[0];
    totalLegs = route.legs.length;
    for (var i = 0; i < route.legs.length; i++) {
        var routeSegment = i+1;
        if(route.legs[i].via_waypoint[0] === undefined) continue;

        document.getElementById('waypoints').value = '';
        var via_waypoint_count = route.legs[i].via_waypoint.length;
        queue = 0;
        for(var bi = 0; bi < via_waypoint_count; bi++)
        {
            var count = 0;

            var lat;
            var lng;

            for (key in route.legs[i].via_waypoint[bi]['location'])
            {
                if(count > 1) break;
                if(count == 0)
                {
                    lat = route.legs[i].via_waypoint[bi]['location'][key];
                    count++;
                    continue;
                }
                lng = route.legs[i].via_waypoint[bi]['location'][key];

                count++;
            }
            reverseGeoCode(new google.maps.LatLng(lat,lng));
        }
    }
}

        function reverseGeoCode(latlng)
    {
        queue += 60;
        setTimeout(function(){
        geocoder.geocode({ 'latLng': latlng }, function(results, status) {
          if (status == google.maps.GeocoderStatus.OK) {
            if (results[1]) {
              document.getElementById('waypoints').value += results[1].formatted_address + '; ';
            }
          } else {
            alert("Geocoder failed due to: " + status);
          }
        });
        }, queue * 10);
    }

我很快从我的JS中提取了这个内容,如果不太清楚,我会逐步发布所有的JS并进行解释。
谢谢。

1
你应该做的是在JS中创建一个新的JSON,确保它不是格式错误的,然后通过AJAX将其传递给PHP,这样就可以解决JSON格式错误的问题。

0

我遇到了同样的问题,不过现在已经解决了。

存储整个DirectionsResponse是完全不必要的。 DirectionsService.route基于传递给它的哈希返回路线。 因此,仅存储该哈希应足以存储路线。
到那时,只有在更好/更快的方式可用时,才可能变成另一条路线。

让我们看一下请求哈希:

request = {
  origin: "Hamburg"
  destination: "Berlin"
  waypoints: [{location: new google.maps.LatLng(53.88,11.51), stopover: false}],
  travelMode: google.maps.DirectionsTravelMode.DRIVING
}

正如Crag之前所提到的,返回的数据类似于JSON而不是JSON本身。 因此,当我们存储这些数据时,需要再次将JSON字符串转换为JSON样式的哈希表。 使用JSON.stringify()将要存储在数据库中的路标看起来像这样:

waypoints:
  [location: {
      Ha: 53.88, 
      Ia: 11.51
    },
    stopover: false
  ]

无论何时您想将数据传递给DirectionsService.route,您都可以在之前调用一个函数,它将使用LatLng对象覆盖每个位置:
parse_route_request = function(request) {
  var waypoint, i, len;
  request = JSON.parse(request);
  for (i = 0, len = request.waypoints.length; i < len; i++) {
    waypoint = request.waypoints[_i];
    if (waypoint.location.Ha) {
      waypoint.location = new google.maps.LatLng(waypoint.location.Ha, waypoint.location.Ia);
    }
  }
  return request;
};

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接