0

I am creating a travel portal with places marked by google map markers. I have a JSON file with data, I load it by jQuery getJSON and in .done() I make a loop to create all markers like below:

<!DOCTYPE html>
<html lang="pl">
<head>
  <meta charset="utf-8">
  <script src="https://maps.googleapis.com/maps/api/js?key=[APIKEY]"></script>
  <script src="js/jquery-3.3.1.min.js"></script>
  <script type="text/javascript">
  var map;
  function initMap() {
    var mapOptions = {
      center: new google.maps.LatLng(51.4717161, 21.4709998),
      zoom: 11
    };
    map = new google.maps.Map(document.getElementById("map"), mapOptions);
  }
  </script>
  <style>
    html, body, #map {
      height: 100%;
    }
  </style>
</head>
<body onload="initMap()">
  <div id="map">
  </div>
</div>
<script>
$(function() {
  $.ajax({
    beforeSend: function(xhr) {
      if (xhr.overrideMimeType) {
        xhr.overrideMimeType("application/json");
      }
    }
  });

  $.getJSON("js/data.json")
  .done(function(data) {
    $.each(data, function(i, item) {
      var latLng = new google.maps.LatLng(item.latitude, item.longitude);
      var marker = new google.maps.Marker({
        position: latLng
      });
      marker.setMap(map);
    });
  })
  .fail(function() {
    var content = '<p>Błąd wczytywania danych!</p>';
    $('#sidebar').html(content);
  });
});
</script>
</body>
</html>

Main problem is that the markers shows once at first loading but after reloading page they disapear. The problem is in the Google Chrome 63, Firefox 57.04.

Is this problem caused by that the loop is in the .done() method?

I tried solutions from this post Google maps API v3 - Marker disappears after setPosition but not works.

I readed google maps move marker with lat/lng from ajax success returned data too.

Here is a data from file:

[
    {
      "id": 1,
      "category": "preserve",
      "title": "Rezerwat Miodne",
      "description": "Lorem psum dolor sit amet...",
      "latitude": "51.3789751",
      "longitude": "21.4606515",
      "photo": "miodne-splash.jpg"
    },
    {
      "id": 2,
      "category": "preserve",
      "title": "Rezerwat Okólny Ług",
      "description": "Lorem psum dolor sit amet...",
      "latitude": "51.4302652",
      "longitude": "21.570949",
      "photo": "lugi-helenowskie-splash.jpg"
    }
  ]

Any suggestions?

NetPax
  • 111
  • 1
  • 6

0 Answers0