devdar
devdar

Reputation: 5654

Using Ajax call to place several custom markers on Google Map

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}]

; 

Upvotes: 1

Views: 4149

Answers (3)

Beetroot-Beetroot
Beetroot-Beetroot

Reputation: 18078

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.

Upvotes: 3

devdar
devdar

Reputation: 5654

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); 

Upvotes: 0

charlietfl
charlietfl

Reputation: 171690

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

Upvotes: -1

Related Questions