1

I have an Ajax function that gets an array of markers data from the database and displays it on a Google Map. I was sucessful at getting one marker to display however i placed the ajax function on a button click event. The event fires sucessfully without any errors.

The data is returned in the form of json object. The markers are not getting drawn to the map. Under is the code:

Ajax Function

  $('#getCitizens').click(function(){

        var mapOptions = {center: new google.maps.LatLng(10.670044,-61.515305),
                         zoom: 16,
                         mapTypeId: google.maps.MapTypeId.ROADMAP
         };

        var map = new google.maps.Map(document.getElementById("map_canvas"),mapOptions);     


        var citizens = (function(){         
                        var citizens = null;
                    $.ajax({
                        type: 'GET',
                        async : false,
                        global: 'false',
                        url: 'getListOfMarkers.htm',
                        headers : {Accept : 'application/json'},
                        dataType: 'json',
                        success: function(data){
                            citizens = data;
                        }               
                    });
                    return citizens;            
                  })();          

              for(var i= 0; i< citizens.length;i++){

                  console.log(citizens[i].name +' | '+citizens[i].socialSecurityNumber +' | '+citizens[i].latlng);

                  var markerType = citizens[i].citizenType


                  if(markerType = 2){
                      var citizen_icon = new google.maps.MarkerImage('resources/icons/a_new.ico',new google.maps.Size(100,106),new google.maps.Point(0,0),new google.maps.Point(50,50));
                  }else if(markerType = 3){
                      var b_icon = new google.maps.MarkerImage('resources/icons/b_new.ico',new google.maps.Size(100,106),new google.maps.Point(0,0),new google.maps.Point(50,50));

                  }else if(markerType = 4){
                      var citizen_icon = new google.maps.MarkerImage('resources/icons/c_new.ico',new google.maps.Size(100,106),new google.maps.Point(0,0),new google.maps.Point(50,50));
                  }


              var citizenPosition = new google.maps.LatLng(citizens[i].latlng);
              var citizenName = citizens[i].name;
              var citizenMarker = new google.maps.Marker({
                  position: citizenPosition,
                  map:map,
                  icon:citizen_icon,
                  title:citizenName

              });

          }


     })

JSON DATA

{"name":"Damien Edwards","latlng":"10.67023300000000,-61.51530500000000","socialSecurityNumber":194302025,"citizenType":3},

{"name":"Raj Hassen","latlng":"10.67030000000000,-61.51530500000000","socialSecurityNumber":198501011,"citizenType":2},

{"name":"Richard Gibbs","latlng":"10.670044,-61.515305","socialSecurityNumber":198501012,"citizenType":2},

{"name":"Sylvester Macintosh","latlng":"10.670044,-61.515305","socialSecurityNumber":1985010122,"citizenType":3},

{"name":"Howard Bugario","latlng":"10.670044,-61.515305","socialSecurityNumber":1985121244,"citizenType":4},

{"name":"Lawerence Figaro","latlng":"10.670044,-61.515305","socialSecurityNumber":1985121245,"citizenType":4},

{"name":"Jessie Small","latlng":"10.670044,-61.515305","socialSecurityNumber":1999020214,"citizenType":3}]

; 
Kara
  • 6,115
  • 16
  • 50
  • 57
devdar
  • 5,564
  • 28
  • 100
  • 153
  • Some testing showed that latlng is returning Latlng Position - (NaN, NaN) i think i passed it in as one varible i need think i need to separate them and pass two separate parameters one for lat and one for lng into var citizenPosition = new google.maps.LatLng(citizens[i].latlng); – devdar May 05 '13 at 23:45
  • possible duplicate of [How to return the response from an AJAX call?](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call) – Qantas 94 Heavy Feb 27 '14 at 13:06

3 Answers3

3

Despite heroic attempts to establish citizens, the asynchronicity of $.ajax() dictates that it will always be null at the time the for loop executes.

Try this :

$('#getCitizens').on('click', function() {
    var mapOptions = {
        center: new google.maps.LatLng(10.670044, -61.515305),
        zoom: 16,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);     
    $.ajax({
        type: 'GET',
        async : true,
        global: 'false',
        url: 'getListOfMarkers.htm',
        headers : {Accept: 'application/json'},
        dataType: 'json'
    }).done(function(citizens) {
        var markerSrcs = [
            null,
            null,
            'resources/icons/a_new.ico',
            'resources/icons/b_new.ico',
            'resources/icons/c_new.ico'
        ];
        $.each(citizens, function(i, c) {
            console.log(c.name + ' | ' + c.socialSecurityNumber + ' | ' + c.latln);
            var src = markerSrcs[c.citizenType];
            if(src) {
                new google.maps.Marker({
                    position: new google.maps.LatLng(c.lat, c.lng),
                    map: map,
                    icon: new google.maps.MarkerImage( src, new google.maps.Size(100, 106), new google.maps.Point(0, 0), new google.maps.Point(50, 50) ),
                    title: c.name
              });
            }
        });
    });
});

I can't see why you should need to create a new map each time new citizen markers are created. It's more typical to create one map and reuse it. To do so you would need to keep a reference to the markers (in an array) so they can be removed before adding new ones.

Beetroot-Beetroot
  • 18,022
  • 3
  • 37
  • 44
  • Can you explain how you select the icons at var markerSrcs = [ null, null, 'resources/icons/criminal_new.ico', 'resources/icons/victim_new.ico', 'resources/icons/suspect_new.ico' ]; – devdar May 06 '13 at 00:54
  • the icons get selected based on a value of the citizen type being 2,3,4 you code works thou but how ? I never user jquery like that before i mean i have seen developers used it – devdar May 06 '13 at 00:55
  • my code works as well except for the fact that i create the new map each time as you rightfully indicated – devdar May 06 '13 at 00:56
  • also citizens is not null at the time of execution it gets executed the issues was resolved by passing the lat long parameters like i indicated in my answer above – devdar May 06 '13 at 00:58
  • 1
    dev_darin, that way you avoid the rather clumsy if/else if/else if structure by simply indexing into the array, which is made possible by `citizen.citizenType` being an integer. The two nulls at [0] and [1] are present to force the first actual src url into position [2]. – Beetroot-Beetroot May 06 '13 at 01:00
  • so if other citizenTypes are added lets say one with id 1 then i remove one of the nulls and if lets say one with 6 is added i add two nulls after the 4th element in the array? – devdar May 06 '13 at 01:07
  • 1
    "also citizens is not null " .... Whoops I didn't notice, you're using `asynch:false` which is a no-no as it won't work in all browsers. If you change `asynch:true` (or just delete the option to give default behaviour) then you will find that what I said is correct. – Beetroot-Beetroot May 06 '13 at 01:14
  • ohhhh waw you like a guru at this lol. can i keep in touch with you mr. please give me your email addy or somthing plz lol – devdar May 06 '13 at 01:17
  • 1
    "so if other citizenTypes are added ...", yes, just make sure there's an entry in the right position in `markerSrcs` for every `.citizenType` the server is likely to return. – Beetroot-Beetroot May 06 '13 at 01:17
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/29459/discussion-between-dev-darin-and-beetroot-beetroot) – devdar May 06 '13 at 01:18
  • dev_darin, there are plenty of guys here who are at least as experienced as me. As long as you ask clear well phrased questions, then you will generally attract an answer - sometimes with astonishing speed. – Beetroot-Beetroot May 06 '13 at 01:24
0

The problem was really related at this point :

var citizenPosition = new google.maps.LatLng(citizens[i].latlng);

google.maps.LatLng() accepts two parameters one for lat and one for lng i passed only one parameter which was concatenated to form latlng. The isses was resolved by:

var citizenPosition = new google.maps.LatLng(citizens[i].lat, citizens[i].lng); 
devdar
  • 5,564
  • 28
  • 100
  • 153
-1

AJAX is asynchronous so you can't return the response ( citizens) from a function the way you are doing , it will be still null.

The easiest is to consume the data within the success callback:

$.ajax({
    type: 'GET',
   /* async: false,*/   /* don't use async:false , it is deprecated and bad practice*/
    global: 'false',
    url: 'getListOfMarkers.htm',
    headers: {
        Accept: 'application/json'
    },
    dataType: 'json',
    success: function (data) {
        var citizens = data;
        /* run all marker code here*/
        for (var i = 0; i < citizens.length; i++) {.......
        }
});

Also am curious about url being .htm ,is not common for sending json

charlietfl
  • 170,828
  • 13
  • 121
  • 150
  • will try this .htm is what i have in the @RequestParam its a SpringMVC app it works for me thou – devdar May 05 '13 at 23:53