Создайте профиль высоты из массива координат полилинии

Я создал полилинию, используя массив координат с кодом, адаптированным из https://google-developers.appspot.com/maps/documentation/javascript/examples/polyline-simple

Хотя первым (и, вероятно, худшим) методом построения линии был просто огромный список точек широты и долготы. Все еще изучаю приемы программирования, приношу свои извинения. Я географ, а не программист!

Я хочу получить высоту от этой линии и создать график профиля высоты. Я новичок в JS и не знаю, как отлаживать то, что не работает. Кажется, я не могу заполнить массив путей координатами полилинии.

В настоящее время он настроен на отправку bikeCourseCoordinates в новый массив, который затем будет использоваться в качестве пути. Я пробовал, просто используя массив bikeCourseCoordinates в качестве «пути», но это тоже не сработало.

Онлайн (но не рабочая версия) здесь: http://geography.uoregon.edu:50000/bentesting/map_try3.html


function drawPath() {

  // Create a new chart in the elevation_chart DIV.
  chart = new google.visualization.ColumnChart(document.getElementById('elevation_chart'));

  var path = new Array;
  path.push(bikeCourseCoordinates);


  // Create a PathElevationRequest object using this array.
  var pathRequest = {
    'path': path,
    'samples': 256
  }

  // Initiate the path request.
  elevator.getElevationAlongPath(pathRequest, plotElevation);
}

// Takes an array of ElevationResult objects, draws the path on the map
// and plots the elevation profile on a Visualization API ColumnChart.
function plotElevation(results, status) {
  if (status == google.maps.ElevationStatus.OK) {
    elevations = results;

    // Extract the elevation samples from the returned results
    // and store them in an array of LatLngs.
    var elevationPath = [];
    for (var i = 0; i < results.length; i++) {
      elevationPath.push(elevations[i].location);
    }

    // Extract the data from which to populate the chart.
    // Because the samples are equidistant, the 'Sample'
    // column here does double duty as distance along the
    // X axis.
    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]);
    }

    // Draw the chart using the data within its DIV.
    document.getElementById('elevation_chart').style.display = 'block';
    chart.draw(data, {
      width: 640,
      height: 200,
      legend: 'none',
      titleY: 'Elevation (m)'
    });
  }
}

person Ben Metcalfe    schedule 13.06.2012    source источник


Ответы (2)


Вы пытаетесь воспроизвести третий пример на этой странице? https://developers.google.com/maps/customize

Если да, то я сделал это, но без графа эффектов

вот мой код

это у тебя в голове

script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true"
script type="text/javascript" src="https://www.google.com/jsapi"
script src="https://www.google.com/uds/?file=visualization&amp;v=1&amp;packages=columnchart" type="text/javascript"

и это в нижнем колонтитуле прямо перед тегом body

var elevator;
var map;
var chart;
var infowindow = new google.maps.InfoWindow();
var polyline;
var mapCenter = new google.maps.LatLng(-21.745585792425,165.91141052497);


// Load the Visualization API and the columnchart package.
google.load("visualization", "1", {packages: ["columnchart"]});


function initialize() {
    var mapOptions = {
        center: mapCenter,
        zoom: 13,
        mapTypeId: 'terrain'
    };

    map = new google.maps.Map(document.getElementById("map"), mapOptions);

    // Create an ElevationService.
    elevator = new google.maps.ElevationService();

    // Draw the path, using the Visualization API and the Elevation service.
    drawPath();
}


function drawPath() {

    // Create a new chart in the elevation_chart DIV.
    chart = new google.visualization.ColumnChart(document.getElementById('elevation-chart'));

    var path = bikeCourseCoordinates;

    // Create a PathElevationRequest object using this array.
    // Ask for 256 samples along that path.
    var pathRequest = {
        'path': path,
        'samples': 256
    }

    // Initiate the path request.
    elevator.getElevationAlongPath(pathRequest, plotElevation);
}



function plotElevation(results, status) {
  if (status == google.maps.ElevationStatus.OK) {
    elevations = results;

    // Extract the elevation samples from the returned results
    // and store them in an array of LatLngs.
    var elevationPath = [];
    for (var i = 0; i < results.length; i++) {
      elevationPath.push(elevations[i].location);
    }

    // Display a polyline of the elevation path.
    var pathOptions = {
      path: elevationPath,
      strokeColor: '#0000CC',
      opacity: 0.9,
      map: map
    }
    polyline = new google.maps.Polyline(pathOptions);

    // Extract the data from which to populate the chart.
    // Because the samples are equidistant, the 'Sample'
    // column here does double duty as distance along the
    // X axis.
    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]);
    }

    // Draw the chart using the data within its DIV.
    document.getElementById('elevation-chart').style.display = 'block';
    chart.draw(data, {
      width: 960,
      height: 300,
      legend: 'none',
      titleY: 'Elevation (m)'
    });
  }
}



initialize();
person user10078    schedule 22.07.2012

Я не смог найти проблему, но вот некоторые наблюдения, которые могут помочь:

I tried it just using the bikeCourseCoordinates array as the 'path'

Согласно Maps API, pathRequest должно быть:

var pathRequest = {
    'path': bikeCourseCoordinates,
    'samples': 256
}

Далее я думаю следующую начальную часть, т.е.:

var whitney = new google.maps.LatLng(36.578581, -118.291994);
...
...
var panamintsprings = new google.maps.LatLng(36.339722, -117.467778);
var badwater = new google.maps.LatLng(36.23998, -116.83171);

var bikeCourseCoordinates = [
            new google.maps.LatLng(47.67609435030702, -116.7896032333374),

который находится непосредственно внутри первого встроенного тега <script>, должен вызываться только после загрузки библиотеки карт. Я бы поместил все это в другую функцию, скажем, myInit, а затем вызвал бы myInit из вашей текущей функции с именем initialize.

Причина вышеизложенного заключается в том, что, хотя вы включаете тег script для включения карт API maps.googleapis.com/maps/api/js?sensor=false, браузер продолжит выполнение следующего блока скрипта, содержащего whitney= new google.maps.Lat, потому что maps.googleapis.com является внешним скриптом, и я думаю, что эти внешние скрипты загружены. асинхронно.

person Kayo    schedule 13.06.2012