Иконки в Google Maps - PullRequest
       28

Иконки в Google Maps

0 голосов
/ 01 июля 2019

Я написал скрипт, который позволял бы мне добавлять свой собственный значок для точек на картах Google, однако только 2 из 3 отображаемых значков являются моими.Другая - это красная точка по умолчанию (это первый маркер, который неверен).Я не могу понять, почему он показывает по умолчанию, а не мой обычай.

  <script type="text/javascript">
    var markers = [{
        "title": 'Northern NJ',
        "lat": '40.248',
        "lng": '-73.580',
        "description": '<p>test</P>.'
      },
      {
        "title": 'Central NJ',
        "lat": '39.763',
        "lng": '-73.710',
        "description": '<p>test</P>.'
      },
      {
        "title": 'Southern NJ',
        "lat": '39.161',
        "lng": '-74.098',
        "description": '<p>test</P>.'
      },
    ];
    window.onload = function() {
      LoadMap();
    }

    function LoadMap() {
      var mapOptions = {
        center: new google.maps.LatLng(markers[0].lat, markers[0].lng),
        zoom: 5,
        streetViewControl: false,
        mapTypeId: 'satellite'
      };
      var map = new google.maps.Map(document.getElementById("dvMap"), mapOptions);

      //Create and open InfoWindow.
      var infoWindow = new google.maps.InfoWindow();

      for (var i = 0; i < markers.length; i++) {
        var data = markers[i];
        var myLatlng = new google.maps.LatLng(data.lat, data.lng);
        var marker = new google.maps.Marker({
          position: myLatlng,
          map: map,
          icon: icon,
          title: data.title
        });
        var icon = {
          url: 'https://static.wixstatic.com/media/e09925_8ec9d5e526f94859b5348b41e3daba74~mv2.png'
        };
        var ctaLayer = new google.maps.KmlLayer({
          url: 'https://docs.google.com/uc?id=1razdqFzFB_MWvExuehRUiqhgAeDBXZOI&amp;export=kml',
          map: map
        });

        //Attach click event to the marker.
        (function(marker, data) {
          google.maps.event.addListener(marker, "click", function(e) {
            //Wrap the content inside an HTML DIV in order to set height and width of InfoWindow.
            infoWindow.setContent("<div style = 'width:400px;min-height:150px'>" + data.description + "</div>");
            infoWindow.open(map, marker);
          });
        })(marker, data);
      }
    }

  </script>

Я надеюсь, что кто-то может понять, почему только 2 из них появляются.

1 Ответ

1 голос
/ 01 июля 2019

Вы определяете icon после создания первого маркера. Переместите это определение перед первым маркером (или за пределами цикла), и оно работает.

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

screenshot of resulting map

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

/* Always set the map height explicitly to define the size of the div
 * element that contains the map. */

#dvMap {
  height: 100%;
}


/* Optional: Makes the sample page fill the window. */

html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
}
<div id="dvMap"></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>
<script type="text/javascript">
  var markers = [{
      "title": 'Northern NJ',
      "lat": '40.248',
      "lng": '-73.580',
      "description": '<p>test</P>.'
    },
    {
      "title": 'Central NJ',
      "lat": '39.763',
      "lng": '-73.710',
      "description": '<p>test</P>.'
    },
    {
      "title": 'Southern NJ',
      "lat": '39.161',
      "lng": '-74.098',
      "description": '<p>test</P>.'
    },
  ];
  window.onload = function() {
    LoadMap();
  }

  function LoadMap() {
    var mapOptions = {
      center: new google.maps.LatLng(markers[0].lat, markers[0].lng),
      zoom: 5,
      streetViewControl: false,
      mapTypeId: 'satellite'
    };
    var map = new google.maps.Map(document.getElementById("dvMap"), mapOptions);

    //Create and open InfoWindow.
    var infoWindow = new google.maps.InfoWindow();
    var icon = {
      url: 'https://static.wixstatic.com/media/e09925_8ec9d5e526f94859b5348b41e3daba74~mv2.png'
    };
    for (var i = 0; i < markers.length; i++) {
      var data = markers[i];
      var myLatlng = new google.maps.LatLng(data.lat, data.lng);
      var marker = new google.maps.Marker({
        position: myLatlng,
        map: map,
        icon: icon,
        title: data.title
      });
      var ctaLayer = new google.maps.KmlLayer({
        url: 'https://docs.google.com/uc?id=1razdqFzFB_MWvExuehRUiqhgAeDBXZOI&amp;export=kml',
        map: map
      });

      //Attach click event to the marker.
      (function(marker, data) {
        google.maps.event.addListener(marker, "click", function(e) {
          //Wrap the content inside an HTML DIV in order to set height and width of InfoWindow.
          infoWindow.setContent("<div style = 'width:400px;min-height:150px'>" + data.description + "</div>");
          infoWindow.open(map, marker);
        });
      })(marker, data);
    }
  }
</script>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...