Owen
Owen

Reputation: 431

Google Maps: load markers from JSON

I have the following JS which processes a form, returns the results as JSON and then should plot the json as markers on the map. Although I do get a json response, nothing is plotted. I'm not very familiar with Javascript, so could someone let me know what the error is below?

Thanks

The JSON:

[
    {
        "lat": "53.598660370500596",
        "lng": "-113.59166319101564"
    }
]

The Javascript

$(function () {
    $('#search').click(function () {
        var projectNumber = $('#project_number').val();
        var setdistance = $('#setdistance').val();
        var companyType = $('#company_type').val();

        //syntax - $.post('filename', {data}, function(response){});
        $.post('business_location_get_map.php', {
            project_number: projectNumber,
            setdistance: setdistance,
            company_type: companyType
        }, function (ret) {
            $('#result').html(ret);
        });
    });
});

function initialize() {
    var mapOptions = {
        center: new google.maps.LatLng(53.5435640000, -113.5),
        zoom: 8
    };
    var map = new google.maps.Map(document.getElementById("map_canvas"),
    mapOptions);
}

google.maps.event.addDomListener(window, 'load', initialize);

function plot() {
    $.getJSON('business_location_get_map.php', function (data) {
        var location;
        $.each(data, function (key, val) {
            addMarker(key.lat, key.lng);
        });
    });
}

function addMarker(lat, lng) {
    marker = new google.maps.Marker({
        position: new google.maps.LatLng(lat, lng),
        map: map,
        icon: redImage
    });
    markersArray.push(marker);
}

google.maps.event.addDomListener('search', 'click', plot);

EDIT:

I've changed

(key.lat, key.lng)

to

(val.lat, val.lng)

I still have the same results,

Upvotes: 0

Views: 1503

Answers (1)

alpakyol
alpakyol

Reputation: 2459

The problem is about $.each()

You are passing key.lat and key.lng to addMarker(), however key is the index of the current element in array. You must use val as it's the real value:

$.each(data, function (key, val) {
   addMarker(val.lat, val.lng);
});

More info about the usage of $.each(): https://api.jquery.com/each/

Upvotes: 1

Related Questions