0

I really don't know how to transform array in object.

what I need is my array could transform into like this object :

    var locations= [
        {lat: -22.9, lng: -43.23},
        {lat: 23.03, lng: 113.12},
        {lat: 23.12, lng: 113.25},
        {lat: -7.24917, lng: 112.75083},
        {lat: -6.323116, lng: 106.870941},
        {lat: 40.69, lng: -73.99},
        {lat: 40.74, lng: -73.94}
    ];

I retrieve the data with ajax :

$(function() {
        $.ajax({
            url         : '<?= base_url('admin/getCustomerLatLong'); ?>',
            method      : 'GET',
            // dataType : 'JSON',
            success     : function(data) {
                console.log(data);
            },
            error: function (jqXHR, textStatus, errorThrown) {
                alert('Error while getting the data. Call the developer!');
            }
        });
    });

and I am using codeigniter, here is getCustomerLatLong function in my controller:

public function getCustomerLatLong() {
    $data = $this->M_customer->getAllCustomers()->result();
    $locations = array();

    foreach ($data as $location) :
        $locations['lat'] = $location->latKota;
        $locations['lng'] = $location->lngKota;
        echo json_encode($locations);
    endforeach;
}

please any answer would be helpful for me, thanks in advance.

1 Answer 1

3

I would imagine you issue is down to the fact that you're using echo inside your loop.

Try changing your controller to something like:

public function getCustomerLatLong()
{
    $data = $this->M_customer->getAllCustomers()->result();
    $locations = [];

    foreach ($data as $location) {

        $locations[] = [
            'lat' => $location->latKota,
            'lng' => $location->lngKota,
        ];
    }

    echo json_encode($locations);

}

You might also need to uncomment dataType : 'JSON',

Hope this helps!

Sign up to request clarification or add additional context in comments.

2 Comments

thanks man, by the way have you ever used google maps marker cluster? I got the problem in set all the markers based on those locations. I have try in many ways but still the markers didn't show up, and my console log didn't show any errors too.
I've haven't used them in a long time, however, if you open up another question I'm sure someone should be able to help :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.