функция щелчка для нескольких кнопок загрузки маркера в одной карте Google javascript - PullRequest
0 голосов
/ 07 июня 2018

Чего я хочу добиться, так это одной карты с несколькими (в данном случае тремя) кнопками, когда вы нажимаете кнопку, карта загружает маркер с расположением этих кнопок.Таким образом, вы можете «прыгать» из одного места в другое.

Я работаю с тремя отдельными функциями и списками событий, но я думаю, что есть способ объединить все это до одной функции?Рабочее решение закомментировано в примере кода ниже ...

<div id="floating-panel">
<input id="address-1" class="address" value="Paris" type="button">
<input id="address-2" class="address" value="London"  type="button">
<input id="address-3" class="address"  value="New York" type="button">

var address = null;

function initMap() {    

        var geocoder = new google.maps.Geocoder();

        var map = new google.maps.Map(document.getElementById('map'), {
            zoom: @MapZoom,
            center: { lat: @MapCenterLat, lng: @MapCenterLng}
    });

    document.getElementByClassName('address').addEventListener('click', function () {
            address = this.value();
            geocodeAddress(geocoder, map);
    });

        //document.getElementById('address-1').addEventListener('click', function () {
        //    geocodeAddress1(geocoder, map);
        //});
        //document.getElementById('address-2').addEventListener('click', function () {
        //    geocodeAddress2(geocoder, map);
        //});
        //document.getElementById('address-2').addEventListener('click', function () {
        //    geocodeAddress3(geocoder, map);
        //});

 }

function geocodeAddress(geocoder, resultsMap) {

    geocoder.geocode({ 'address': address }, function (results, status) {
        if (status === 'OK') {
            resultsMap.setCenter(results[0].geometry.location);
            var marker = new google.maps.Marker({
                map: resultsMap,
                position: results[0].geometry.location
            });
        } else {
            alert('Geocode was not successful for the following reason: ' + status);
        }
    });
}

//function geocodeAddress1(geocoder, resultsMap) {

//    geocoder.geocode({ 'address': address }, function (results, status) {
//        if (status === 'OK') {
//            resultsMap.setCenter(results[0].geometry.location);
//            var marker = new google.maps.Marker({
//                map: resultsMap,
//                position: results[0].geometry.location
//            });
//        } else {
//            alert('Geocode was not successful for the following reason: ' + status);
//        }
//    });
//}
//function geocodeAddress2(geocoder, resultsMap) {

//    geocoder.geocode({ 'address': address }, function (results, status) {
//        if (status === 'OK') {
//            resultsMap.setCenter(results[0].geometry.location);
//            var marker = new google.maps.Marker({
//                map: resultsMap,
//                position: results[0].geometry.location
//            });
//        } else {
//            alert('Geocode was not successful for the following reason: ' + status);
//        }
//    });
//}
//function geocodeAddress3(geocoder, resultsMap) {

//    geocoder.geocode({ 'address': address }, function (results, status) {
//        if (status === 'OK') {
//            resultsMap.setCenter(results[0].geometry.location);
//            var marker = new google.maps.Marker({
//                map: resultsMap,
//                position: results[0].geometry.location
//            });
//        } else {
//            alert('Geocode was not successful for the following reason: ' + status);
//        }
//    });
//}

1 Ответ

0 голосов
/ 07 июня 2018

Я получаю ошибку JavaScript с вашим кодом: Uncaught TypeError: document.getElementByClassName is not a function.document.getElementByClassName не существует.Имя функции - document.getElementsByClassName (множественное число), и оно возвращает массив элементов DOM.Обработайте через массив добавление прослушивателей кликов (или используйте jQuery с соответствующим селектором).Кроме того, this.value не является функцией (измените this.value() на this.value).

var elems = document.getElementsByClassName('address');
for (var i = 0; i < elems.length; i++) {
  elems[i].addEventListener('click', function() {
    geocodeAddress(this.value, geocoder, map);
  });
};

function geocodeAddress(address, geocoder, resultsMap) {
  geocoder.geocode({
    'address': address
  }, function(results, status) {
    if (status === 'OK') {
      resultsMap.setCenter(results[0].geometry.location);
      var marker = new google.maps.Marker({
        map: resultsMap,
        position: results[0].geometry.location
      });
    } else {
      alert('Geocode was not successful for the following reason: ' + status);
    }
  });
}

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

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

var geocoder;

function initMap() {
  geocoder = new google.maps.Geocoder();
  var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 13,
    center: {
      lat: 37.4419,
      lng: -122.1419
    }
  });

  var elems = document.getElementsByClassName('address');
  for (var i = 0; i < elems.length; i++) {
    elems[i].addEventListener('click', function() {
      geocodeAddress(this.value, geocoder, map);
    });
  };
}

function geocodeAddress(address, geocoder, resultsMap) {
  geocoder.geocode({
    'address': address
  }, function(results, status) {
    if (status === 'OK') {
      resultsMap.setCenter(results[0].geometry.location);
      var marker = new google.maps.Marker({
        map: resultsMap,
        position: results[0].geometry.location
      });
    } else {
      alert('Geocode was not successful for the following reason: ' + status);
    }
  });
}

google.maps.event.addDomListener(window, "load", initMap);
html,
body,
#map {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px;
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="floating-panel">
  <input id="address-1" class="address" value="Paris" type="button" />
  <input id="address-2" class="address" value="London" type="button" />
  <input id="address-3" class="address" value="New York" type="button" />
</div>
<div id="map"></div>
...