Google Maps Javascript API:沿方向的高程图

时间:2019-07-29 09:51:25

标签: google-maps

我正在使用Google Maps API来构建网站,而在构建高程图时遇到了麻烦。 Google gives an example in their documentation,但它指的是声明一些航路点,而这不是我的情况。我正在使用Directions API,因此Google会自动构建路径。

这是我的代码:

    <script>
      function initMap() {
        var directionsDisplay = new google.maps.DirectionsRenderer;
        var directionsService = new google.maps.DirectionsService;

        var map = new google.maps.Map(document.getElementById('map'), {
            zoom: 14,
            mapTypeId: 'terrain',
            disableDefaultUI: true,
            fullscreenControl: true,
            scaleControl: true,
            zoomControl: true
        });
        directionsDisplay.setMap(map);

        calculateAndDisplayRoute(directionsService, directionsDisplay);
      }

      function calculateAndDisplayRoute(directionsService, directionsDisplay) {
        var mapTravelMode = "DRIVING";
        var mapOrigin = {lat: 46.573240, lng: 26.927229};
        var mapDestination = {lat: 46.517151, lng: 27.081692};
        var waypts = [
        {location: {lat:46.5857174, lng: 26.9553385}, stopover: false},
        {location: {lat:46.581699, lng: 26.999611}, stopover: false},
        ];

        directionsService.route({
          origin: mapOrigin,  // Origin.
          destination: mapDestination,  // Destination.
          waypoints: waypts, // Waypoints
          travelMode: google.maps.TravelMode[mapTravelMode],
          avoidHighways: true,
          avoidTolls: true,
          optimizeWaypoints: true
        }, function(response, status) {
          if (status == 'OK') {
            directionsDisplay.setDirections(response);
            console.log(response);
          } else {
            window.alert('[directionsService] A aparut o eroare: ' + status);
          }
        });

      }
    </script>

有人可以帮我吗?

1 个答案:

答案 0 :(得分:1)

将从路线服务返回的路径传递到高程服务。

在路线服务的回调中,将返回结果中的overview_path传递给getElevationAlongPath函数作为路径。

if (status == 'OK') {
    directionsDisplay.setDirections(response);
    elevationService.getElevationAlongPath({
      path: response.routes[0].overview_path,
      samples: SAMPLES
    }, plotElevation);

    console.log(response);
  } else {
    window.alert('[directionsService] error: status: ' + status);

海拔服务的回调位置为:

  // Takes an array of ElevationResult objects 
  // and plots the elevation profile on a GViz ColumnChart
  function plotElevation(results) {
    elevations = results;

    var path = [];
    for (var i = 0; i < results.length; i++) {
      path.push(elevations[i].location);
    }

    var data = new google.visualization.DataTable();
    data.addColumn('string', 'Sample');
    data.addColumn('number', 'Elevation');
    for (var i = 0; i < results.length; i++) {
      data.addRow(['', elevations[i].elevation]);
    }

    document.getElementById('chart_div').style.display = 'block';
    chart.draw(data, {
      width: 512,
      height: 200,
      legend: 'none',
      titleY: 'Elevation (m)',
      focusBorderColor: '#00ff00'
    });
  }

proof of concept fiddle

screenshot of resulting map

代码段:

(由于错误而无法正常工作:Uncaught DOMException: Blocked a frame with origin "null" from accessing a cross-origin frame.

/* Always set the map height explicitly to define the size of the div
 * element that contains the map. */

#map {
  height: 50%;
}

#chart_div {
  height: 50%;
}


/* Optional: Makes the sample page fill the window. */

html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
}
<div id="map"></div>
<div id="chart_div"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script type="text/javascript" src="https://www.google.com/jsapi"></script>

<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<script>
var SAMPLES = 256; 
var mousemarker = null;
var polyline = null;

  // Load the Visualization API and the piechart package.
  google.load("visualization", "1", {
    packages: ["columnchart"]
  });
  // Set a callback to run when the Google Visualization API is loaded.
  google.setOnLoadCallback(initMap);

  function initMap() {
    var directionsDisplay = new google.maps.DirectionsRenderer;
    var directionsService = new google.maps.DirectionsService;

    var map = new google.maps.Map(document.getElementById('map'), {
      zoom: 14,
      mapTypeId: 'terrain',
      disableDefaultUI: true,
      fullscreenControl: true,
      scaleControl: true,
      zoomControl: true
    });
    chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
    elevationService = new google.maps.ElevationService();

    directionsDisplay.setMap(map);

    calculateAndDisplayRoute(directionsService, directionsDisplay);
  }

  function calculateAndDisplayRoute(directionsService, directionsDisplay) {
    var mapTravelMode = "DRIVING";
    var mapOrigin = {
      lat: 46.573240,
      lng: 26.927229
    };
    var mapDestination = {
      lat: 46.517151,
      lng: 27.081692
    };
    var waypts = [{
        location: {
          lat: 46.5857174,
          lng: 26.9553385
        },
        stopover: false
      },
      {
        location: {
          lat: 46.581699,
          lng: 26.999611
        },
        stopover: false
      },
    ];

    directionsService.route({
      origin: mapOrigin, // Origin.
      destination: mapDestination, // Destination.
      waypoints: waypts, // Waypoints
      travelMode: google.maps.TravelMode[mapTravelMode],
      avoidHighways: true,
      avoidTolls: true,
      optimizeWaypoints: true
    }, function(response, status) {
      if (status == 'OK') {
        directionsDisplay.setDirections(response);
        elevationService.getElevationAlongPath({
          path: response.routes[0].overview_path,
          samples: SAMPLES
        }, plotElevation);

        console.log(response);
      } else {
        window.alert('[directionsService] A aparut o eroare: ' + status);
      }
    });

  }
  // Takes an array of ElevationResult objects, draws the path on the map
  // and plots the elevation profile on a GViz ColumnChart
  function plotElevation(results) {
    elevations = results;

    var path = [];
    for (var i = 0; i < results.length; i++) {
      path.push(elevations[i].location);
    }
    var data = new google.visualization.DataTable();
    data.addColumn('string', 'Sample');
    data.addColumn('number', 'Elevation');
    for (var i = 0; i < results.length; i++) {
      data.addRow(['', elevations[i].elevation]);
    }

    document.getElementById('chart_div').style.display = 'block';
    chart.draw(data, {
      width: 512,
      height: 200,
      legend: 'none',
      titleY: 'Elevation (m)',
      focusBorderColor: '#00ff00'
    });
  }
</script>