Как заполнить InfoWindow API Карт Google содержимым из файла JSON - PullRequest
0 голосов
/ 24 апреля 2020

Я искал на форуме (бесконечно), пробуя все, что нашел, но ничего не работает. У меня есть следующий код. Я хочу иметь возможность щелкнуть по одному из маркеров и получить всплывающее окно InfoWindow с уникальным контентом, полученным из соответствующего JSON, чтобы в окне были Location, Date-Time и Details, и я могу назначить им другой html / css. Ничего не работает Любая помощь?

HTML

<head>
<title>Data Layer: Simple</title>
<meta name="viewport" content="initial-scale=1.0">
<meta charset="utf-8">
<link href="style.css" rel="stylesheet" type="text/css">
</head>

<body>

<div id="mymap"></div>

<script type="text/javascript" src="script.js"></script>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=REDACTED&callback=initMap">
</script>

</body>

</html>

CSS

@charset "UTF-8";

  #mymap {
        height: 100%;
      }

 html, body {
        height: 100%;
        margin: 0;
        padding: 0;
      }

JAVASCRIPT

  var ufomap;
  var infowindow = new google.maps.InfoWindow();

function initMap() {
        ufomap = new google.maps.Map(document.getElementById('mymap'), {
          zoom: 4,
          center: {lat:37.0902,lng:-95.7129}
        });

        ufomap.data.loadGeoJson('json.geojson');

        }

JSON

{
   "type":"FeatureCollection",
   "features":[
      {
         "type":"Feature",
         "properties":{
            "Location":"Greensburg, PA",
            "Date-Time":"1969-01-01T10:00:00",
            "Shape”:”Circle”,
            "Details":"Possible contact with Visitor as a child When I was 2 to 4 years old",
            "Latitude":"40.33569572",
            "Longitude":"-79.55026848"
         },
         "geometry":{
            "type":"Point",
            "coordinates":[
               -79.550268,
               40.335696
            ]
         }
      },
{
   "type":"FeatureCollection",
   "features":[
      {
         "type":"Feature",
         "properties":{
            "Location”:”Smithtown, PA",
            "Date-Time":"1979-01-01T10:00:00",
            "Shape”:”Square”,
            "Details”:”Bright lights flashing“,
            "Latitude":"44.33569572",
            "Longitude":"-78.55026848"
         },
         "geometry":{
            "type":"Point",
            "coordinates":[
               -78.550268,
               44.335696
            ]
         }
      }

1 Ответ

1 голос
/ 24 апреля 2020
  1. Ваш Geo JSON недопустим (в консоли JavaScript сообщается об ошибках). Запустите его через geojsonlint.com и исправьте все ошибки (или исправьте ошибки, сообщенные в консоли JavaScript). То, что вы опубликовали, исправлено:
{
  "type": "FeatureCollection",
  "features": [{
      "type": "Feature",
      "properties": {
        "Location": "Greensburg, PA",
        "Date-Time": "1969-01-01T10:00:00",
        "Shape": "Circle",
        "Details": "Possible contact with Visitor as a child When I was 2 to 4 years old",
        "Latitude": "40.33569572",
        "Longitude": "-79.55026848"
      },
      "geometry": {
        "type": "Point",
        "coordinates": [
          -79.550268,
          40.335696
        ]
      }
    },
    {
      "type": "Feature",
      "properties": {
        "Location": "Smithtown, PA",
        "Date-Time": "1979-01-01T10:00:00",
        "Shape": "Square",
        "Details": "Bright lights flashing",
        "Latitude": "44.33569572",
        "Longitude": "-78.55026848"
      },
      "geometry": {
        "type": "Point",
        "coordinates": [
          -78.550268,
          44.335696
        ]
      }
    }
  ]
}
Если я укажу правильность и использую код из соответствующего вопроса: API карт Google получает информационное окно по щелчку с гео json файлом , это работает (но с небольшой поправкой на pixelOffset InfoWindow делает это лучше).

подтверждение концепции скрипта

screenshot of resulting map

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

var ufomap;

function initMap() {
  ufomap = new google.maps.Map(document.getElementById('mymap'), {
    zoom: 4,
    center: {
      lat: 37.0902,
      lng: -95.7129
    }
  });
  var infowindow = new google.maps.InfoWindow();
  // ufomap.data.loadGeoJson('json.geojson');
  ufomap.data.addGeoJson(geoJson);
  ufomap.data.addListener('click', function(event) {
    console.log(event);
    // Location, Date-Time, and Details
    let location = event.feature.getProperty('Location');
    let datetime = event.feature.getProperty('Date-Time');
    let details = event.feature.getProperty('Details');
    let html = location + "<br>" + datetime + "<br>" + details;
    infowindow.setContent(html); // show the html variable in the infowindow
    infowindow.setPosition(event.latLng);
    infowindow.setOptions({
      pixelOffset: new google.maps.Size(0, -42)
    }); // move the infowindow up 42 pixels to the top of the default marker icon
    infowindow.open(ufomap);
  });
}
var geoJson = {
  "type": "FeatureCollection",
  "features": [{
      "type": "Feature",
      "properties": {
        "Location": "Greensburg, PA",
        "Date-Time": "1969-01-01T10:00:00",
        "Shape": "Circle",
        "Details": "Possible contact with Visitor as a child When I was 2 to 4 years old",
        "Latitude": "40.33569572",
        "Longitude": "-79.55026848"
      },
      "geometry": {
        "type": "Point",
        "coordinates": [-79.550268,
          40.335696
        ]
      }
    },
    {
      "type": "Feature",
      "properties": {
        "Location": "Smithtown, PA",
        "Date-Time": "1979-01-01T10:00:00",
        "Shape": "Square",
        "Details": "Bright lights flashing",
        "Latitude": "44.33569572",
        "Longitude": "-78.55026848"
      },
      "geometry": {
        "type": "Point",
        "coordinates": [-78.550268,
          44.335696
        ]
      }
    }
  ]
}
#mymap {
  height: 100%;
}

html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
}
<div id="mymap"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap">
</script>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...