Uncaught TypeError: Can not read property 'split' of undefined

1

Hello

In my JavaScript code I get the following error: "Uncaught TypeError: Can not read property 'split' of undefined". As I am new to the area, I do not understand how to solve the problem very well, can someone help me identify it?

var map = new google.maps.Map(document.getElementById("map"), mapOptions);
var marks = [];
for (var i = 0; i < location.length; i++) {
    marks[i] = createMark(i); /*ERRO*/
}

function createMark() {
    var imagePath = "marker" + (i + 1) + ".png";
    var image = imagePath;
    var markers = [];
    var lat = locations[i].split(',')[0]; /*ERRO*/
    var long = locations[i].split(',')[1];
    var location = new google.maps.LatLng(lat, long);
    var marker = new google.maps.Marker({
        position: location,
        map: map,
        icon: image
    });
    marker.setTitle("Cliente");
    var textOrder = "<strong> Ponto: </strong> " + (i + 1) + ". <br> <strong> Latitude: </strong>" + lat + ", <strong> Longitude: </strong>" + long;
    var infowindow = new google.maps.InfoWindow({
        content: textOrder
    });
    google.maps.event.addListener(marker, "click", function() {
        infowindow.open(map, marker);
    });
}
    
asked by anonymous 14.03.2017 / 13:14

2 answers

2

3 things to fix:

function createMark(i) { // <--------------- mudança 1
    var imagePath = "marker" + (i + 1) + ".png";
    var image = imagePath;
    var markers = [];
    if (!locations[i]) return null; // <--------------- mudança 2
    var lat = locations[i].split(',')[0]; /*ERRO*/
    var long = locations[i].split(',')[1];
    var location = new google.maps.LatLng(lat, long);
    var marker = new google.maps.Marker({
        position: location,
        map: map,
        icon: image
    });
    marker.setTitle("Cliente");
    var textOrder = "<strong> Ponto: </strong> " + (i + 1) + ". <br> <strong> Latitude: </strong>" + lat + ", <strong> Longitude: </strong>" + long;
    var infowindow = new google.maps.InfoWindow({
        content: textOrder
    });
    google.maps.event.addListener(marker, "click", function() {
        infowindow.open(map, marker);
    });
    return marker; // <--------------- mudança 3
}

The first one is missing the i within the scope of the function. The second is a safeguard if locations[i] does not have what is expected.
The third is for the function to return something to be saved in marks[i]

    
14.03.2017 / 13:51
2

In the line where the error is occurring, you pass the variable i as a parameter to the function createMark (), but it happens that this function is not expecting any parameters:

for (var i = 0; i < location.length; i++) {
    marks[i] = createMark(i); /*ERRO*/
}

What you should do is change the line

function createMark() {

To

function createMark(i) {
    
14.03.2017 / 13:42