0

我有以下字符串形式的谷歌地图路线

NewRoute = '{"start":{"lat":51.5479454,"lng":-0.04057739999996102},"end":{"lat":51.5166787,"lng":-0.0596227999999428},"waypoints":[[51.5474343,-0.07557889999998224]]}';

我想加载到地图上。如何将字符串 NewRoute 转换为数组 os 以便可以在以下函数中使用?

function showRoute(oViewMapButton)
{
    ButtonName = oViewMapButton.name;
    if(ButtonName.length == 13){
            var RouteName = "strWayPoints_r" + ButtonName.slice(-1);
            var DistanceName = "strDistance_r" + ButtonName.slice(-1);
    }else{
        var RouteName = "strWayPoints_r" + ButtonName.slice(-2);
        var DistanceName = "strDistance_r" + ButtonName.slice(-2);
    }

    oRoute = document.getElementById(RouteName);
    var NewRoute = oRoute.value;

    var os = [];
    os = NewRoute;

    var wp = [];
    for(var i=0;i<os.waypoints.length;i++)
    wp[i] = {'location': new google.maps.LatLng(os.waypoints[i][0], os.waypoints[i][1]),'stopover':false }


    $( "#hid_FieldName3" ).val(DistanceName);
    $( "#map-form" ).dialog( "open" );

    var request = {
        origin:new google.maps.LatLng(os.start.lat,os.start.lng),
        destination:new google.maps.LatLng(os.end.lat,os.end.lng),
        waypoints: wp,
        travelMode: google.maps.DirectionsTravelMode.DRIVING
    };
    directionsService.route(request, function(response, status) {
        if (status == google.maps.DirectionsStatus.OK) {
            directionsDisplay.setDirections(response);
        } else {
            alert("There was an unknown error in your request. Requeststatus: \n\n"+status);
        }
    });
 }
4

3 回答 3

1

你是怎么得到那个字符串的?它看起来像一个 javascript 对象。如果您在不使用外部引号的情况下分配它,您将获得一个对象并可以像这样使用它:

var route = {
    "start": {"lat": 51.5479454, "lng": -0.04057739999996102},
    "end": {"lat": 51.5166787, "lng": -0.0596227999999428},
    "waypoints": [[51.5474343, -0.07557889999998224]]
};

route.start
route.start.lat
route.waypoints[0][1]
etc.

关于 javascript 对象:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects

于 2013-09-14T22:27:20.150 回答
1

假设 JSON 是具有 RouteName id 的元素的值,只需修改以下行:

var NewRoute = oRoute.value;

至:

var NewRoute = JSON.parse(oRoute.value);
于 2013-09-14T22:29:33.410 回答
1

你可以试试这个(只是转换json成一个对象)

var NewRoute = '{"start":{"lat":51.5479454,"lng":-0.04057739999996102},"end":{"lat":51.5166787,"lng":-0.0596227999999428},"waypoints":[[51.5474343,-0.07557889999998224]]}';
var os = JSON.parse(NewRoute);

因此,现在您可以像使用它一样使用它,也可以os.start.latos.waypoints.length您的函数中使用它。

在您的函数中,替换以下行

var NewRoute = oRoute.value;

与以下行

var NewRoute = JSON.parse(oRoute.value);

而已。

于 2013-09-14T22:33:07.213 回答