@para_mid

Из-за чего появляется ошибка?

b38294d0e246405d8a906ea9ef6e3b97.gif
Собственно, ругаться будет и на остальные data.title, data.lng и т.д
При чем всё работает как надо, но ошибка мозолит глаз
var markers_1 = [{
  "title": 'Alibag',
  "lat": '1.641400',
  "lng": '2.872200',
  "description": 'Alibaug is a coastal town and a municipal council in Raigad District in the Konkan region of Maharashtra, India.'
}, {
  "title": 'Aurangabad',
  "lat": '3.879700',
  "lng": '4.335300',
  "description": 'Aurangabad'
}, {
  "title": 'Dombivli',
  "lat": '5.218400',
  "lng": '6.086700',
  "description": 'Dombivli'
}, {
  "title": 'Lonavla',
  "lat": '7.750000',
  "lng": '8.416700',
  "description": 'Lonavla'
}];
var markers_2 = [{
  "title": '21',
  "lat": '9.641400',
  "lng": '10.872200',
  "description": 'Alibaug is a coastal town and a municipal council in Raigad District in the Konkan region of Maharashtra, India.'
}, {
  "title": '22',
  "lat": '11.879700',
  "lng": '12.335300',
  "description": 'Aurangabad'
}, {
  "title": '23',
  "lat": '13.218400',
  "lng": '14.086700',
  "description": 'Dombivli'
}, {
  "title": '24',
  "lat": '15.750000',
  "lng": '16.416700',
  "description": 'Lonavla'
}];
var markers_3 = [{
  "title": '31',
  "lat": '17.641400',
  "lng": '18.872200',
  "description": 'Alibaug is a coastal town and a municipal council in Raigad District in the Konkan region of Maharashtra, India.'
}, {
  "title": '32',
  "lat": '20.879700',
  "lng": '21.335300',
  "description": 'Aurangabad'
}, {
  "title": '33',
  "lat": '22.218400',
  "lng": '23.086700',
  "description": 'Dombivli'
}, {
  "title": '34',
  "lat": '24.750000',
  "lng": '25.416700',
  "description": 'Lonavla'
}];
var markers_4 = [{
  "title": '41',
  "lat": '26.641400',
  "lng": '27.872200',
  "description": 'Alibaug is a coastal town and a municipal council in Raigad District in the Konkan region of Maharashtra, India.'
}, {
  "title": '42',
  "lat": '28.879700',
  "lng": '29.335300',
  "description": 'Aurangabad'
}, {
  "title": '43',
  "lat": '30.218400',
  "lng": '31.086700',
  "description": 'Dombivli'
}, {
  "title": '44',
  "lat": '32.750000',
  "lng": '33.416700',
  "description": 'Lonavla'
}];


var cate_amount= 5; //количество категорий
function refresh_cate(){

		 for (var i = 1; i < cate_amount+1; i++) {
  document.getElementById("list_"+i).style.display = "none";
}
}

function refresh_cate_first(){

		 for (var i = 2; i < cate_amount+1; i++) {
  document.getElementById("list_"+i).style.display = "none";
}
}




var map;
var markerObjects = [];



function initialize() {

    var myOptions = {
      center: new google.maps.LatLng(markers_1[0].lat, markers_1[0].lng),
      zoom: 7,
      mapTypeId: google.maps.MapTypeId.ROADMAP,

      disableDefaultUI: true,
		   styles: [{"featureType":"administrative","elementType":"all","stylers":[{"saturation":"-100"}]},{"featureType":"administrative.province","elementType":"all","stylers":[{"visibility":"off"}]},{"featureType":"landscape","elementType":"all","stylers":[{"saturation":-100},{"lightness":65},{"visibility":"on"}]},{"featureType":"poi","elementType":"all","stylers":[{"saturation":-100},{"lightness":"50"},{"visibility":"simplified"}]},{"featureType":"road","elementType":"all","stylers":[{"saturation":"-100"}]},{"featureType":"road.highway","elementType":"all","stylers":[{"visibility":"simplified"}]},{"featureType":"road.arterial","elementType":"all","stylers":[{"lightness":"30"}]},{"featureType":"road.local","elementType":"all","stylers":[{"lightness":"40"}]},{"featureType":"transit","elementType":"all","stylers":[{"saturation":-100},{"visibility":"simplified"}]},{"featureType":"water","elementType":"geometry","stylers":[{"hue":"#ffff00"},{"lightness":-25},{"saturation":-97}]},{"featureType":"water","elementType":"labels","stylers":[{"lightness":-25},{"saturation":-100}]}]
    };

    map = new google.maps.Map(document.getElementById("map"), myOptions);

  	// drop markers one by one
   place();

  } // initialize




function place(){
	
	map.setZoom(5);
	
	var selectedOption = $('#objects_category').find(":selected").val();
	
	var data_id = eval(`markers_${selectedOption}`);
	
	map.setCenter(new google.maps.LatLng(data_id[0].lat, data_id[0].lng));
	
	
	//очищаем все предыдущие
	$('.list-group-item').remove();
	for (markerIndex in markerObjects) {
   markerObjects[markerIndex].setMap(null);
}
 
	
	 var i = 0;
     var interval = setInterval(function() {
		 
	   var data = data_id[i];
		 
 var myLatlng = new google.maps.LatLng(data.lat, data.lng);//вот на эту ругается

      // initial icon
      var defaultMarkerColor = '999';
      var pinImage = new google.maps.MarkerImage("https://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|" + defaultMarkerColor);

      // marker object for the marker
      var marker = new google.maps.Marker({
        position: myLatlng,
        map: map,
        title: data.title,
        animation: google.maps.Animation.DROP,
        icon: pinImage
      });

      // store in a global array
      var markerIndex = markerObjects.push(marker) - 1;

      // click listener on a marker itself
      google.maps.event.addListener(markerObjects[markerIndex], 'click', function() {
        var marker = this;
       
      });

      // create a row in the overlay table and bind onhover
      var $row = $('<li>')
        .addClass('list-group-item')
        .html(data.title)
        .on('mouseenter', function() {
          var marker = markerObjects[markerIndex];
         
        })
        .on('mouseleave', function() {
          var marker = markerObjects[markerIndex];
         
        });
		 
      // create colorpicker and append to row
      $cp_div = $('<a href="#" ></a>');
    


      $row.appendTo('#overlay');

      // continue iteration
      i++;
      if (i ==data.length) {
        clearInterval(interval);
      }
    }, 100);
}


google.maps.event.addDomListener(window, 'load', initialize);
  • Вопрос задан
  • 181 просмотр
Пригласить эксперта
Ответы на вопрос 1
lazalu68
@lazalu68
Salmon
Первое.

cannot read property 'lat' of undefined


"Не может прочитать свойство «lat» неопределенного" © Google Translate
Вы пытаетесь прочитать свойство "lat" у неопределённого объекта.

Второе - вы делаете дикую дичь. Разве в теле "цикла" у вас есть хоть одна асинхронная операция, зачем использовать интервал? Собственно, этот момент и привел к ошибке, в цикле вы бы не смогли допустить такой ошибки. Дичь например есть в строке 137.

Третье - чтобы найти ошибку, посмотрите на ваш "цикл" и посмотрите какое условие должно выполниться чтобы цикл завершился. Это условие неправильно.
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы