Информационное окно в Google Maps не загружается - PullRequest
0 голосов
/ 09 мая 2020

У меня проблемы с отображением информационного окна. Я проверял код миллион раз, но не могу его понять. Я вставил свой код ниже. Пожалуйста, помогите мне найти проблему.

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

Я использую Google Chrome.

//Javascript function to load map
function initMap() {
  var myLatlng = new google.maps.LatLng(37.09024, -95.712891);
  var mapOptions = {
     zoom: 4,
     center: myLatlng,
     scrollwheel: false, 
 }

 var map = new google.maps.Map(document.getElementById("regularMap"), mapOptions);
 var infoWindow = new google.maps.InfoWindow;
 geojson_url = 'https://raw.githubusercontent.com/eyeshu98/dummy/master/geodata.json',
 map.data.loadGeoJson(geojson_url, null, loadMarkers)

 function loadMarkers() {

 map.data.forEach(function(feature) {

 // geojson format is [longitude, latitude] but google maps marker position attribute
 // expects [latitude, longitude]
 var latitude = feature.getGeometry().get().lat()
 var longitude = feature.getGeometry().get().lng()
 var titleText = feature.getProperty('Location ID')
 var infowincontent = document.createElement('div');
  var strong = document.createElement('strong');
  strong.textContent = titleText
  infowincontent.appendChild(strong);
  infowincontent.appendChild(document.createElement('br'));
 console.log(infowincontent);

 var marker = new google.maps.Marker({
   position: {lat: latitude, lng:longitude},
   map: map,
   clickable: true
  });
  marker.addListener('click', function() {
     infoWindow.close();
      infoWindow.setContent(infowincontent);
      infoWindow.open(map, marker);
    });

 });

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

Ответы [ 2 ]

0 голосов
/ 10 мая 2020

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

Вам просто нужно добавить прослушиватель для события щелчка на вашем Geo JSON слой и показать информационное окно из функции обратного вызова вашего слушателя. Обратите внимание, что объект события в случае слоя Geo JSON содержит элемент, по которому был выполнен щелчок.

Посмотрите следующий фрагмент кода:

function initMap() {
  var myLatlng = new google.maps.LatLng(37.09024, -95.712891);
  var mapOptions = {
     zoom: 4,
     center: myLatlng,
     scrollwheel: false, 
 }

 var map = new google.maps.Map(document.getElementById("regularMap"), mapOptions);
 var infoWindow = new google.maps.InfoWindow();
 geojson_url = 'https://raw.githubusercontent.com/eyeshu98/dummy/master/geodata.json',
 
 map.data.loadGeoJson(geojson_url);
 map.data.addListener('click', function(event) {
   var feature = event.feature;
   var latitude = feature.getGeometry().get().lat()
   var longitude = feature.getGeometry().get().lng()
   var titleText = feature.getProperty('Location ID')
   var infowincontent = document.createElement('div');
   var strong = document.createElement('strong');
   strong.textContent = titleText
   infowincontent.appendChild(strong);
   infowincontent.appendChild(document.createElement('br'));
   console.log(infowincontent);
   infoWindow.close();
   infoWindow.setContent(infowincontent);
   infoWindow.setPosition(feature.getGeometry().get());
   infoWindow.open(map);
 });
}

google.maps.event.addDomListener(window, 'load', initMap);
/* Always set the map height explicitly to define the size of the div
 * element that contains the map. */
#regularMap {
  height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html, body {
  height: 100%;
  margin: 0;
  padding: 0;
}
<div id="regularMap"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>

Надеюсь, это поможет!

0 голосов
/ 09 мая 2020

У вас есть два набора маркеров: загруженные с помощью loadGeoJson и набор маркеров, который вы добавите позже. Те из DataLayer находятся над теми, у которых есть прослушиватель щелчков, блокируя щелчок.

Самое простое исправление, скрыть маркеры из DataLayer с помощью: концептуальной скрипки

screenshot of map with open infowindow

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

function initMap() {
  var myLatlng = new google.maps.LatLng(37.09024, -95.712891);
  var mapOptions = {
     zoom: 4,
     center: myLatlng,
     scrollwheel: false, 
 }

 var map = new google.maps.Map(document.getElementById("regularMap"), mapOptions);
 var infoWindow = new google.maps.InfoWindow;
 geojson_url = 'https://raw.githubusercontent.com/eyeshu98/dummy/master/geodata.json',
 map.data.loadGeoJson(geojson_url, null, loadMarkers);
 map.data.setMap(null); // hide the datalayer

 function loadMarkers() {

 map.data.forEach(function(feature) {

 // geojson format is [longitude, latitude] but google maps marker position attribute
 // expects [latitude, longitude]
 var latitude = feature.getGeometry().get().lat()
 var longitude = feature.getGeometry().get().lng()
 var titleText = feature.getProperty('Location ID')
 var infowincontent = document.createElement('div');
  var strong = document.createElement('strong');
  strong.textContent = titleText
  infowincontent.appendChild(strong);
  infowincontent.appendChild(document.createElement('br'));
 console.log(infowincontent);

 var marker = new google.maps.Marker({
   position: {lat: latitude, lng:longitude},
   map: map,
   clickable: true
  });
  marker.addListener('click', function() {
     infoWindow.close();
      infoWindow.setContent(infowincontent);
      infoWindow.open(map, marker);
    });

 });

}
}
google.maps.event.addDomListener(window, 'load', initMap);
/* Always set the map height explicitly to define the size of the div
 * element that contains the map. */
#regularMap {
  height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html, body {
  height: 100%;
  margin: 0;
  padding: 0;
}
<div id="regularMap"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...