«Uncaught TypeError: this.setValues ​​не является функцией» с использованием Google Maps API v3 - PullRequest
0 голосов
/ 15 октября 2018

Попытка изменить пример и использовать класс markerLabel вместо google.maps.marker.Искал решение здесь, но ничего не смог найти.

markerwithlabel объявлено как var marker = new MarkerWithLabel({

Я получаю эту ошибку

Uncaught TypeError: this.setValues is not a function

Пожалуйста, проверьте нижеприведенный код.https://codepen.io/anon/pen/LgOzRO

Я попытался включить только код, связанный с этой проблемой, и минимальный код, необходимый для ее воспроизведения.

 var map;
var locations = [];

function initialiseMap() {
  $.getJSON("https://sheets.googleapis.com/v4/spreadsheets/1fBLlw8xlO_yhL8rYfFlQnzvKR-swEtE7NRX41ysARCk/values/Sheet1!A2:Q?key=AIzaSyD112yF6ORTtrx1-ugfhJLcx1VHDOla1Vs", function(data) {
        // data.values contains the array of rows from the spreadsheet. Each row is also an array of cell values.
        // Modify the code below to suit the structure of your spreadsheet.
        $(data.values).each(function() {
            var location = {};
                location.title = this[2];
                location.latitude = parseFloat(this[15]);
                location.longitude = parseFloat(this[16]);

                locations.push(location);
        });

      // Center on (0, 0). Map center and zoom will reconfigure later (fitbounds method)
      var mapOptions = {
        zoom: 10,
        center: new google.maps.LatLng(0, 0)
      };
      var map = new google.maps.Map(document.getElementById('map'), mapOptions);
      setLocations(map, locations);
  });
}


function setLocations(map, locations) {
  var bounds = new google.maps.LatLngBounds();
  // Create nice, customised pop-up boxes, to appear when the marker is clicked on
  var infowindow = new google.maps.InfoWindow({
    content: "Content String"
  });
  for (var i = 0; i < locations.length; i++) {
    var new_marker = createMarker(map, locations[i], infowindow);
    bounds.extend(new_marker.position);
  }
  map.fitBounds(bounds);
}

function createMarker(map, location, infowindow) {

  // Modify the code below to suit the structure of your spreadsheet (stored in variable 'location')
  var position = {
    lat: parseFloat(location.latitude),
    lng: parseFloat(location.longitude)
  };
  var marker = new MarkerWithLabel({
    position: position,
    map: map,
    title: location.title,
     labelClass: "labels", // the CSS class for the label
        labelInBackground: false,
        icon: pinSymbol('red')
  });
  google.maps.event.addListener(marker, 'click', function() {

  });
  return marker;
}

function pinSymbol(color) {
    return {
        path: 'M 0,0 C -2,-20 -10,-22 -10,-30 A 10,10 0 1,1 10,-30 C 10,-22 2,-20 0,0 z',
        fillColor: color,
        fillOpacity: 1,
        strokeColor: '#000',
        strokeWeight: 2,
        scale: 2
    };
}

1 Ответ

0 голосов
/ 15 октября 2018

У вас проблема с секвенированием на стороне HTML.При загрузке Javascript с тегом <script> вы должны использовать async или defer, а не оба.В этом случае Google API должен быть загружен после Javascript страницы таким образом, чтобы обратный вызов initialiseMap определялся во времени, поэтому он должен иметь атрибут defer.Тем не менее, API Google должен быть загружен перед загрузкой V3 MarkerWithLabel, поэтому скрипту V3 также требуется атрибут defer , а должен идти после скрипта API Google.

Так что ваш HTML должен быть

<script defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyD112yF6ORTtrx1-ugfhJLcx1VHDOla1Vs&callback=initialiseMap"></script>
<script defer src="https://cdn.rawgit.com/googlemaps/v3-utility-library/master/markerwithlabel/src/markerwithlabel.js"></script>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...