0

I first read a sets of coordinates in my local drive, then put them in the xcoord and y coord to be start,waypts,destination which will be plotted on Google Map.

But i discovered that, once the coodinates exceeding a certain number,the route is not plotted anymore,but a road map without and route. changing travelmode also changing the number of effective waypoints. What can be done when i have >100 coordinates to be plotted? Also, i would like to change all the marker into default one but not the green one with letters on it.(After 26 points the marker become normal again.) Thank you very much.

I was first using the example provided in a question about 8 waypoints, which is here:

Plotting more than 8 waypoints in Google Maps v3

My code are as follow:

xcoord = [];
ycoord = [];
stops = [] ;

document.getElementById('file').onchange = function(){
alert('4');
var file = this.files[0];

var reader = new FileReader();
reader.onload = function(progressEvent){

var lines = this.result.split('\n');
for(var line = 0; line < lines.length; line++){
  //alert(lines[line]);
  var split = [];
  split = lines[line].split(',');
  window.xcoord.push(split[0]);
  window.ycoord.push(split[1]);    
}
alert('finish');    
}

reader.readAsText(file); 

};  

jQuery(function() {

document.getElementById('button').onclick = function initMap(){
for(i = 0;i<xcoord.length;i++){
window.stops.push({"Geometry":{"Latitude":xcoord[i],"Longitude":ycoord[i]}});}
var map = new window.google.maps.Map(document.getElementById("map"));

// new up complex objects before passing them around
var directionsDisplay = new window.google.maps.DirectionsRenderer();
var directionsService = new window.google.maps.DirectionsService();

Tour_startUp(stops);

window.tour.loadMap(map, directionsDisplay);
window.tour.fitBounds(map);

if (stops.length > 1)
    window.tour.calcRoute(directionsService, directionsDisplay);}});



function Tour_startUp(stops) {
if (!window.tour) window.tour = {
    updateStops: function (newStops) {
        stops = newStops;
    },
    // map: google map object
    // directionsDisplay: google directionsDisplay object (comes in empty)
    loadMap: function (map, directionsDisplay) {
        var myOptions = {
            zoom: 13,
            center: new window.google.maps.LatLng(22.2830, 114.200), 
            mapTypeId: window.google.maps.MapTypeId.ROADMAP
        };
        map.setOptions(myOptions);
        directionsDisplay.setMap(map);
    },
    fitBounds: function (map) {
        var bounds = new window.google.maps.LatLngBounds();

        // extend bounds for each record
        jQuery.each(stops, function (key, val) {
            var myLatlng = new window.google.maps.LatLng(val.Geometry.Latitude, val.Geometry.Longitude);
            bounds.extend(myLatlng);
        });
        map.fitBounds(bounds);
    },
    calcRoute: function (directionsService, directionsDisplay) {
        var batches = [];
        var itemsPerBatch = 10; // google API max = 10 - 1 start, 1 stop, and 8 waypoints
        var itemsCounter = 0;
        var wayptsExist = stops.length > 0;

        while (wayptsExist) {
            var subBatch = [];
            var subitemsCounter = 0;

            for (var j = itemsCounter; j < stops.length; j++) {
                subitemsCounter++;
                subBatch.push({
                    location: new window.google.maps.LatLng(stops[j].Geometry.Latitude, stops[j].Geometry.Longitude),
                    stopover: true
                });
                if (subitemsCounter == itemsPerBatch)
                    break;
            }

            itemsCounter += subitemsCounter;
            batches.push(subBatch);
            wayptsExist = itemsCounter < stops.length;
            // If it runs again there are still points. Minus 1 before continuing to
            // start up with end of previous tour leg
            itemsCounter--;
        }

        // now we should have a 2 dimensional array with a list of a list of waypoints
        var combinedResults;
        var unsortedResults = [{}]; // to hold the counter and the results themselves as they come back, to later sort
        var directionsResultsReturned = 0;

        for (var k = 0; k < batches.length; k++) {
            var lastIndex = batches[k].length - 1;
            var start = batches[k][0].location;
            var end = batches[k][lastIndex].location;

            // trim first and last entry from array
            var waypts = [];
            waypts = batches[k];
            waypts.splice(0, 1);
            waypts.splice(waypts.length - 1, 1);

            var request = {
                origin: start,
                destination: end,
                waypoints: waypts,
                optimizeWaypoints: true,
                travelMode: window.google.maps.TravelMode.WALKING
            };
            (function (kk) {
                directionsService.route(request, function (result, status) {
                    if (status == window.google.maps.DirectionsStatus.OK) {

                        var unsortedResult = { order: kk, result: result };
                        unsortedResults.push(unsortedResult);

                        directionsResultsReturned++;

                        if (directionsResultsReturned == batches.length) // we've received all the results. put to map
                        {
                            // sort the returned values into their correct order
                            unsortedResults.sort(function (a, b) { return parseFloat(a.order) - parseFloat(b.order); });
                            var count = 0;
                            for (var key in unsortedResults) {
                                if (unsortedResults[key].result != null) {
                                    if (unsortedResults.hasOwnProperty(key)) {
                                        if (count == 0) // first results. new up the combinedResults object
                                            combinedResults = unsortedResults[key].result;
                                        else {
                                            // only building up legs, overview_path, and bounds in my consolidated object. This is not a complete
                                            // directionResults object, but enough to draw a path on the map, which is all I need
                                            combinedResults.routes[0].legs = combinedResults.routes[0].legs.concat(unsortedResults[key].result.routes[0].legs);
                                            combinedResults.routes[0].overview_path = combinedResults.routes[0].overview_path.concat(unsortedResults[key].result.routes[0].overview_path);

                                            combinedResults.routes[0].bounds = combinedResults.routes[0].bounds.extend(unsortedResults[key].result.routes[0].bounds.getNorthEast());
                                            combinedResults.routes[0].bounds = combinedResults.routes[0].bounds.extend(unsortedResults[key].result.routes[0].bounds.getSouthWest());
                                        }
                                        count++;
                                    }
                                }
                            }
                            directionsDisplay.setDirections(combinedResults);
                            var legs = combinedResults.routes[0].legs;
                            // alert(legs.length);
                            for (var i=0; i < legs.length;i++){
              var markerletter = "A".charCodeAt(0);
              markerletter += i;
                              markerletter = String.fromCharCode(markerletter);
                              createMarker(directionsDisplay.getMap(),legs[i].start_location,"marker"+i,"some text for marker "+i+"<br>"+legs[i].start_address,markerletter);
                            }
                            var i=legs.length;
                            var markerletter = "A".charCodeAt(0);
                markerletter += i;
                            markerletter = String.fromCharCode(markerletter);
                            createMarker(directionsDisplay.getMap(),legs[legs.length-1].end_location,"marker"+i,"some text for the "+i+"marker<br>"+legs[legs.length-1].end_address,markerletter);
                        }
                    }
                });
            })(k);
        }
    }
};

}

Community
  • 1
  • 1
PSo
  • 958
  • 9
  • 25
  • Will the location of coodinates affect the plotting of the route? I have tried different set of coordinates and the exceeding number of points is not the same, so i guess this is the problem of the coordinates. Some coordinates are provided:[coordinates1](http://textuploader.com/5pzs0) [coordinates2](http://textuploader.com/5pzsj) – PSo Jan 11 '16 at 04:08
  • Yes. Some locations can not be routed (depending on the travelMode), check the status returned by the DirectionsService for more information. Also, more than 100 coordinates will probably be prohibitively slow. What are you doing that requires plotting 100 points? The directions web service now supports 23 waypoints, so you may be able to use that. – geocodezip Jan 11 '16 at 05:42
  • Hello geocodezip, i checked many questions and you are the best i am sure. The reason why i have those >100 coordinates is that those are my car gps data, but some of them were not on the road directly so i wanted to snap them on the road. Unfortunately, i cannot make that happen. – PSo Jan 11 '16 at 05:57
  • and other thing i would like to do is that,i input my gps data in to script and it generates the corresponding route. I am relatively new to coding and Javascript, this is my first time to code it. I have done a Marker version which i input all gps data and it shows all the markers on the map.But what i really want is an route to be honest. Any suggestions? – PSo Jan 11 '16 at 05:59
  • Look at the [Roads API](https://developers.google.com/maps/documentation/roads/intro). – geocodezip Jan 11 '16 at 06:27
  • And, if i wanted to input sets of coordinates instead of drawing lines, what are the code i needed to delete? The path value means lat,long seperated by | ? function runSnapToRoad(path) { var pathValues = []; for (var i = 0; i < path.getLength(); i++) { pathValues.push(path.getAt(i).toUrlValue()); } $.get('https://roads.googleapis.com/v1/snapToRoads', { interpolate: true, key: apiKey, path: pathValues.join('|') }, function(data) { processSnapToRoadResponse(data); drawSnappedPolyline(); getAndDrawSpeedLimits(); }); } – PSo Jan 11 '16 at 06:56

1 Answers1

0

The Snap to road thing is done via loading coordinates using PHP and then using the google api. the code is as follow(for less than 200 points):

<!DOCTYPE html>
<?php
  $stringJoin = "";
  $stringJoin2 = "";
  $index = 0;
  $handle = fopen($_GET['fileName'], "r");
  if ($handle) {
  while (($line = fgets($handle)) !== false) {
      $index++;
      if ($index ==99 ){
          $stringJoin2 .= trim($line)."|";
      }
      if ($index >= 100) {
        $stringJoin2 .= trim($line)."|";
        if($index == 200){
            break;
        }
        continue;
      }
      $stringJoin .= trim($line)."|";
  }
  fclose($handle); }
  echo $index;
  echo "<br>";
  $stringJoin = substr($stringJoin, 0, -1);
  $stringJoin2 = substr($stringJoin2, 0, -1);
  echo $stringJoin;
  echo "<br>";
  echo $stringJoin2; ?>
<html>
  <head>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">

 <title>Roads API Demo</title>
    <style>
    html, body, #map {
    height: 100%;
    margin: 0px;
    padding: 0px
  }

    #panel {
    position: absolute;
    top: 5px;
    left: 50%;
    margin-left: -180px;
    z-index: 5;
    background-color: #fff;
    padding: 5px;
    border: 1px solid #999;
  }

  #bar {
    width: 240px;
    background-color: rgba(255, 255, 255, 0.75);
    margin: 8px;
    padding: 4px;
    border-radius: 4px;
  }

  #autoc {
    width: 100%;
    box-sizing: border-box;
  }
</style>
   </head>

 <body>
  <input type="button" name="button" id="button">
  <input type="file" name="file" id="file">
   <div id="map"></div>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script
  src="https://maps.googleapis.com/maps/api/js?libraries=drawing,places"></script>
<script>
var apiKey = 'AIzaSyCk5PjtR_spPKrVowRS3A7I3IE4gX6Ctec';

var map;
var drawingManager;
var placeIdArray = [];
var placeIdArray2 = [];
var polylines = [];
var polylines2 = [];
var snappedCoordinates = [];
var snappedCoordinates2 = [];

document.getElementById('button').onclick = function initialize() {
  alert("Start");
  var mapOptions = {
zoom: 13,
center: {lat: 22.3030, lng: 114.200}  };

  map = new google.maps.Map(document.getElementById('map'), mapOptions);
  runSnapToRoad();
  runSnapToRoad2();}

// Snap a user-created polyline to roads and draw the snapped path
function runSnapToRoad() {
   $.get('https://roads.googleapis.com/v1/snapToRoads', {
    interpolate: true,
    key: apiKey,
    path: <?php echo '"'.$stringJoin.'"';?>}, function(data) {
    processSnapToRoadResponse(data);
    drawSnappedPolyline();
    //getAndDrawSpeedLimits(); });}

// Store snapped polyline returned by the snap-to-road method.
function processSnapToRoadResponse(data) {
  snappedCoordinates = [];
  placeIdArray = [];
  for (var i = 0; i < data.snappedPoints.length; i++) {
    var latlng = new google.maps.LatLng(
        data.snappedPoints[i].location.latitude,
        data.snappedPoints[i].location.longitude);
    snappedCoordinates.push(latlng);
    placeIdArray.push(data.snappedPoints[i].placeId);  }}

// Draws the snapped polyline (after processing snap-to-road response).
function drawSnappedPolyline() {
  var snappedPolyline = new google.maps.Polyline({
    path: snappedCoordinates,
    strokeColor: 'black',
    strokeWeight: 3 });

  snappedPolyline.setMap(map);
  polylines.push(snappedPolyline);}

</script>

<div id="bar">
  <p class="auto"><input type="text" id="autoc"/></p>
  <p><a id="clear" href="#">Click here</a> to clear map.</p>
</div>

PSo
  • 958
  • 9
  • 25