Тепловая карта Google Maps работает только тогда, когда данные тепловой карты жестко заданы, а не когда они генерируются с использованием цикла for - PullRequest
1 голос
/ 25 марта 2019

Я пытаюсь построить тепловую карту на Google Maps с помощью API. При использовании жестко закодированного массива объектов LatLng рендеринг работает. Однако, если я тогда попытаюсь удалить жестко закодированный массив и сгенерировать массив, используя цикл for, рендеринг завершится неудачей.

console.log для двух переменных массива дает мне одинаковые объекты.

Здесь приведена js-скрипка: https://jsfiddle.net/arpanio/7weomu5g/61/

2 переменные:

  • Жестко закодированный массив: heatmapData
  • Сгенерированный массив: heatmap_data

Пожалуйста, смотрите строку 87 и строку 88, где я закомментирую и переключаюсь между двумя переменными. Хардкодированный вариант работает. Опция сгенерированного массива не работает. Я печатаю и на консоли, и не вижу никакой разницы в объекте (кроме фактических значений широты и долготы).

Код js воспроизводится ниже:

var map;
var service;
var infowindow;

function initMap() {
  var sydney = new google.maps.LatLng(45.76404, 4.83565);

  infowindow = new google.maps.InfoWindow();

  map = new google.maps.Map(
      document.getElementById('map'), {center: sydney, zoom: 12});
var heatmapData = [
new google.maps.LatLng(45.7523537999999,4.8405),
new google.maps.LatLng(45.7663606,4.8328),
new google.maps.LatLng(45.7603967,4.8557)
];

console.log(heatmapData);

//Data to be obtained from mymap -> KML -> GeoJSON
geo_json = {  
   "type":"FeatureCollection",
   "name":"merged",
   "crs":{  
      "type":"name",
      "properties":{  
         "name":"urn:ogc:def:crs:OGC:1.3:CRS84"
      }
   },
   "features":[  
      {  
         "type":"Feature",
         "properties":{  
            "Name":"Auchan Drive Lyon Saint Priest"
         },
         "geometry":{  
            "type":"Point",
            "coordinates":[  
               4.9252405,
               45.7235401
            ]
         }
      },
      {  
         "type":"Feature",
         "properties":{  
            "Name":"Auchan Drive Saint Genis (Chapônost)"
         },
         "geometry":{  
            "type":"Point",
            "coordinates":[  
               4.76585360000001,
               45.6992269
            ]
         }
      },
      {  
         "type":"Feature",
         "properties":{  
            "Name":"Auchan"
         },
         "geometry":{  
            "type":"Point",
            "coordinates":[  
               4.8008698,
               45.7498202
            ]
         }
      }
   ]
};

//Convert GeoJSON to Google-specific heatmap data
var heatmap_data = [];
for(var i = 0; i < geo_json.features.length; i++) {
    var temp = geo_json.features[i].geometry.coordinates;
  heatmap_data.push(new google.maps.LatLng(temp[0], temp[1]));
  //console.log(temp);
  /* var lat_lng = new google.maps.LatLng(temp[0], temp[1]);
  heatmap_data.push(lat_lng); */
}
console.log(heatmap_data);


var heatmap = new google.maps.visualization.HeatmapLayer({
 /* Problem here */
 data: heatmapData, //This works
 //data: heatmap_data, //This does not
 radius: 50,
  opacity: 0.4
});
heatmap.setMap(map);

  var request = {
    location: sydney,
    radius: '500',
    query: 'Carrefour'
  };

  service = new google.maps.places.PlacesService(map);

  service.textSearch(request, function(results, status) {
    console.log(results);
    if (status === google.maps.places.PlacesServiceStatus.OK) {
      for (var i = 0; i < results.length; i++) {
        createMarker(results[i]);
       //console.log(JSON.stringify(results[i].geometry.location));       
      }

      map.setCenter(results[0].geometry.location);
    }


  });
}

function createMarker(place) {
  var marker = new google.maps.Marker({
    map: map,
    icon: {
      path: google.maps.SymbolPath.CIRCLE,
      scale: 2
    },
    position: place.geometry.location
  });

  google.maps.event.addListener(marker, 'click', function() {
    infowindow.setContent(place.name);
    infowindow.open(map, this);
  });
}

Ответы [ 2 ]

2 голосов
/ 25 марта 2019

Изменить последовательность координат temp переменная -

heatmap_data.push(new google.maps.LatLng(temp[0], temp[1]));

до

heatmap_data.push(new google.maps.LatLng(temp[1], temp[0]));

Рабочая JSFiddle - https://jsfiddle.net/hL7n2fek/

Ваш heatmap генерируется, но с жестко закодированным heatmapData координаты 45.7523537999999,4.8405, который указывает где-то в France, и ваша карта Google инициализируется рядом с теми же координатами.

Но в вашем свойстве geometry объекта geo_json координаты указываются как [4.9252405, 45.7235401], что указывает на местоположение где-то в Somalia. Ваш видимый раздел на карте Google не покрывает это. Если вы увеличите масштаб, вы увидите, что он генерируется.

1 голос
/ 25 марта 2019

GeoJson указывает координаты в порядке [Longitude, Latitude].

Итак, этот код:

heatmap_data.push(new google.maps.LatLng(temp[0], temp[1])); // temp[0] (is Longitude), temp[1] (is Latitude)

должно быть:

heatmap_data.push(new google.maps.LatLng(temp[1], temp[0])); // temp[1] (is Latitude), temp[1] (is Longitude)

обновленная скрипка

screenshot of resulting map

фрагмент кода:

var map;
var service;
var infowindow;

function initMap() {
  var sydney = new google.maps.LatLng(45.76404, 4.83565);

  infowindow = new google.maps.InfoWindow();

  map = new google.maps.Map(
    document.getElementById('map'), {
      center: sydney,
      zoom: 12
    });
  var heatmapData = [
    new google.maps.LatLng(45.7523537999999, 4.8405),
    new google.maps.LatLng(45.7663606, 4.8328),
    new google.maps.LatLng(45.7603967, 4.8557)
  ];

  console.log(heatmapData);

  //Data to be obtained from mymap -> KML -> GeoJSON
  geo_json = {
    "type": "FeatureCollection",
    "name": "merged",
    "crs": {
      "type": "name",
      "properties": {
        "name": "urn:ogc:def:crs:OGC:1.3:CRS84"
      }
    },
    "features": [{
        "type": "Feature",
        "properties": {
          "Name": "Auchan Drive Lyon Saint Priest"
        },
        "geometry": {
          "type": "Point",
          "coordinates": [
            4.8405,
            45.7523537999999
          ]
        }
      },
      {
        "type": "Feature",
        "properties": {
          "Name": "Auchan Drive Saint Genis (Chapônost)"
        },
        "geometry": {
          "type": "Point",
          "coordinates": [
            4.8328,
            45.7663606
          ]
        }
      },
      {
        "type": "Feature",
        "properties": {
          "Name": "Auchan"
        },
        "geometry": {
          "type": "Point",
          "coordinates": [
            4.8557,
            45.7603967
          ]
        }
      }
    ]
  };

  //Convert GeoJSON to Google-specific heatmap data
  var heatmap_data = [];
  for (var i = 0; i < geo_json.features.length; i++) {
    var temp = geo_json.features[i].geometry.coordinates;
    // heatmap_data.push(new google.maps.LatLng(temp[0], temp[1]));
    console.log(temp);
    var lat_lng = new google.maps.LatLng(temp[1], temp[0]);
    heatmap_data.push(lat_lng);
  }
  console.log(heatmap_data);


  var heatmap = new google.maps.visualization.HeatmapLayer({
    /* Problem here */
    // data: heatmapData, //This works
    data: heatmap_data, //This does not
    radius: 50,
    opacity: 0.4
  });
  heatmap.setMap(map);

  var request = {
    location: sydney,
    radius: '500',
    query: 'Carrefour'
  };

  service = new google.maps.places.PlacesService(map);

  service.textSearch(request, function(results, status) {
    console.log(results);
    if (status === google.maps.places.PlacesServiceStatus.OK) {
      for (var i = 0; i < results.length; i++) {
        createMarker(results[i]);
        //console.log(JSON.stringify(results[i].geometry.location));       
      }

      map.setCenter(results[0].geometry.location);
    }


  });
}

function createMarker(place) {
  var marker = new google.maps.Marker({
    map: map,
    icon: {
      path: google.maps.SymbolPath.CIRCLE,
      scale: 2
    },
    position: place.geometry.location
  });

  google.maps.event.addListener(marker, 'click', function() {
    infowindow.setContent(place.name);
    infowindow.open(map, this);
  });
}
html,
body,
#map {
  height: 100%;
  margin: 0;
  padding: 0;
}
<div id="map"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&libraries=places,visualization&callback=initMap" async defer></script>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...