简体   繁体   中英

Google map pin title from json array

I have a map which i am populating from a json array.

I pass a multidimensional array and convert to json:

public List<string[]> locationList { get; set; }

var locs = @Html.Raw(Json.Encode(Model.locationList));

Map code using postcode:

var map;
var elevator;
var myOptions = {
    zoom: 5,
    center: new google.maps.LatLng(53.90, -3.00),
    mapTypeId: 'roadmap'
};

map = new google.maps.Map($('#map_canvas_locations')[0], myOptions);

var latlng;   

for (var i = 0; i < locs.length; i++) {
    var name = locs[i][1];
    var markerdata = $.getJSON('https://maps.googleapis.com/maps/api/geocode/json?address=' + locs[i][0] + '&sensor=false', null, function (data) {
        var p = data.results[0].geometry.location
        latlng = new google.maps.LatLng(p.lat, p.lng);

        new google.maps.Marker({
            position: latlng,
            map: map,
            title: name,
        });           
    });
};

The problem seems to be with title. If I try using json value directly no pins show:

new google.maps.Marker({
            position: latlng,
            map: map,
            title: locs[i][1],
        });

If I try assigning the value to a var I get all the map pins but they all have what seems to be the last entry's title:

var name = locs[i][1];    

new google.maps.Marker({
            position: latlng,
            map: map,
            title: name,
        }); 

What am I doing wrong?

the problem is the options for google.maps.Marker are wrapped in a closure {}

so you end up passing a reference to i which ends up as the last value

use forEach instead of traditional for loop

the presence of the function should allow name to keep it's value

locs.forEach(function (name) {
    var markerdata = $.getJSON('https://maps.googleapis.com/maps/api/geocode/json?address=' + locs[i][0] + '&sensor=false', null, function (data) {
        var p = data.results[0].geometry.location
        latlng = new google.maps.LatLng(p.lat, p.lng);

        new google.maps.Marker({
            position: latlng,
            map: map,
            title: name
        });
    });
});

for more, here's the real answer...
JavaScript closure inside loops

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM