来自geoJSON的Google地图航点

时间:2014-08-12 19:12:52

标签: javascript json google-maps-api-3 geojson

我想从geoJSON文件加载行程。 目前,它有效,但只有两点。

但我需要添加4或5个航点。我的代码只读取了两个第一点并将它们设置为Origin和destination。

这是我的代码

 google.maps.event.addListener(map.data, 'addfeature', function (e) {

    if (e.feature.getGeometry().getType() === 'Point') {
        map.setCenter(e.feature.getGeometry().get());

        if (!origin) origin = e.feature.getGeometry().get(); //if origin does not exist

        else if (!destination) {
            destination = e.feature.getGeometry().get();

            calculate();
        }
    }
});

有什么想法吗? 我必须创建一个循环吗? 或者更改航点的json代码?

这是我的json:

{
"type": "FeatureCollection",
"features":

 [

    { "type": "Feature",
        "geometry": {"type": "Point", "coordinates": [-73.562686, 45.4960413]},
        "properties": {"prop0": "value0"}
    },


    { "type": "Feature",
        "geometry": {"type": "Point", "coordinates": [-73.568367, 45.4933086]},
        "properties": {"prop0": "value0"}
    }
]

  }

谢谢!

2 个答案:

答案 0 :(得分:1)

working fiddle

function calculate() {
    var request = {
        origin: origin,
        waypoints: waypts,
        destination: destination,
        travelMode: google.maps.TravelMode.DRIVING
    };
    directionsDisplay.setPanel(document.getElementById('directions-panel'));
    directionsService.route(request, function (response, status) {
        if (status == google.maps.DirectionsStatus.OK) {
            directionsDisplay.setDirections(response);
        }
    });
}

// global variables
var origin = null;
var destination = null;
var waypts = [];
var infowindow = new google.maps.InfoWindow();
var directionsDisplay = new google.maps.DirectionsRenderer();
var directionsService = new google.maps.DirectionsService();

function initialize() {
    // Create a simple map.
    features = [];
    map = new google.maps.Map(document.getElementById('map-canvas'), {
        zoom: 4,
        center: {
            lat: -28,
            lng: 137.883
        }
    });
    directionsDisplay.setMap(map);
    directionsDisplay.setPanel(document.getElementById('directions-panel'));
    google.maps.event.addListener(map, 'click', function () {
        infowindow.close();
    });
    // process the loaded GeoJSON data.
    google.maps.event.addListener(map.data, 'addfeature', function (e) {
        if (e.feature.getGeometry().getType() === 'Point') {
            map.setCenter(e.feature.getGeometry().get());
            // set the origin to the first point
            if (!origin) origin = e.feature.getGeometry().get();
            // set the destination to the second point
            else waypts.push({
                location: e.feature.getGeometry().get(),
                stopover: true
            });
            // calculate the directions once both origin and destination are set 
            // calculate();
        }
    });
    google.maps.event.addListenerOnce(map, 'idle', function () {
        if (!destination) {
            destination = waypts.pop();
            destination = destination.location;
            // calculate the directions once both origin and destination are set 
            calculate();
        }
    });
    map.data.addGeoJson(data);
}

google.maps.event.addDomListener(window, 'load', initialize);

要解决Dr.Molle关于在加载数据层之前触发idle事件的观点,您可以创建自定义data_idle事件,并在所有点之后触发该事件。 GeoJson已经处理完毕。

updated fiddle

var features_added = 0;
function initialize() {
    // Create a simple map.
    features = [];
    map = new google.maps.Map(document.getElementById('map-canvas'), {
        zoom: 4,
        center: {
            lat: -28,
            lng: 137.883
        }
    });
    directionsDisplay.setMap(map);
    directionsDisplay.setPanel(document.getElementById('directions-panel'));
    google.maps.event.addListener(map, 'click', function () {
        infowindow.close();
    });
    // process the loaded GeoJSON data.
    google.maps.event.addListener(map.data, 'addfeature', function (e) {
        if (e.feature.getGeometry().getType() === 'Point') {
            features_added++;
            map.setCenter(e.feature.getGeometry().get());
            // set the origin to the first point
            if (!origin) origin = e.feature.getGeometry().get();
            // set the destination to the second point
            else waypts.push({
                location: e.feature.getGeometry().get(),
                stopover: true
            });
            setTimeout(function() {features_added--; if (features_added <= 0) google.maps.event.trigger(map, 'data_idle');
                }, 500);
        }
    });
    google.maps.event.addListenerOnce(map, 'data_idle', function () {
        if (!destination) {
            destination = waypts.pop();
            destination = destination.location;
            // calculate the directions once both origin and destination are set 
            calculate();
        }
    });
    map.data.loadGeoJson("http://www.geocodezip.com/directions.json.txt");
}

google.maps.event.addDomListener(window, 'load', initialize);

答案 1 :(得分:0)

问题是您无法访问功能所属的FeatureCollection。在解析geoJSON时,也没有事件会触发(当addfeature-event触发时你永远不会知道它是否是特定FeatureCollection的最后一次)

您可以存储功能的其他属性,例如航点数量。

sample-JSON(包括定义的其他属性,例如,如果某个点是航点,起点或目的地,或者当它是航点的航点时)

{
"type": "FeatureCollection",
"features": [
  {
    "type"        : "Feature",
    "properties"  : {route      :{"id"    :1,
                                  "type"  :"origin",
                                  "points":2
                                 }
                    },
    "geometry"    : {"type"       : "Point",
                     "coordinates":[8.528849, 52.030656]}
  },

  {
    "type"        : "Feature",
    "properties"  : {route        :{"id"    :1,
                                    "type"  :"destination",
                                    "points":2
                                   }
                    },
    "geometry"    : {"type"       : "Point",
                     "coordinates":[11.5819, 48.1351253]}
  },

  {
    "type": "Feature",
    "properties"  : {"route"      :{"id"    :1,
                                    "type"  :"waypoint",
                                    "index" :1,
                                    "points":2
                                   }
                    },
    "geometry"    : {"type"       : "Point",
                     "coordinates":[13.40495,52.52]}
  },

  {
    "type"        : "Feature",
    "properties"  : {route        :{"id":1,
                                    "type":"waypoint",
                                    "index":0,
                                    "points":2
                                   }
                    },
    "geometry"    : {"type"       : "Point",
                     "coordinates":[9.99368, 53.5510846]}
  }
]}

它将属性存储在自定义route - 属性中。

属性是:

  • type(出发地,目的地或航路点)
  • id(路线的一些唯一ID,通过使用您可以定义多条路线的ID)
  • points(为路线定义的航点数)
  • index ...用于类型:waypoint(waypoints-array中航路点的索引,从0开始)

解析这些属性:

 map.data.addListener('addfeature',function(e){
  var geo=  e.feature.getGeometry();
  if(geo.getType()==='Point' && e.feature.getProperty('route')){
    var id    = e.feature.getProperty('route').id,
        type  = e.feature.getProperty('route').type,
        points= e.feature.getProperty('route').points,
        data;
    //the routes will be stored as a property of map.data
    if(!map.data.get('routes')){
        map.data.set('routes',{});
    }
    if(!map.data.get('routes')[id]){
      map.data.get('routes')[id]={waypoints:[],points:points,origin:null,destination:null};
    }

    data= map.data.get('routes')[id];
    switch(type){
      case 'waypoint':
        data.points--;
        data.waypoints[e.feature.getProperty('route').index]={location:geo.get()};
       break;
      default:
        data[type]= geo.get();

    }
    if(!data.points && data.origin && data.destination){
      //parsing of the route is complete
      delete data.points;
      //run the callback, 
      //data is an object suitable to be used as DirectionsRequest
      //you only need to add the desired travelMode
      callback(data);
    }
  }
 });

演示:http://jsfiddle.net/doktormolle/vupkbasc/