1

I want to fetch data (longitude/latitude) from database and return it to draw multiple marker on Google Map using Ajax call.

Below is javascript including ajax :

<script type='text/javascript'>

            (function(){

                var map,marker,latlng,bounds,infowin;
                /* initial locations for map */
                var _lat=5.441771999999999;
                var _lng=100.2936793;

                var id=1;

                function showMap(){
                    /* set the default initial location */
                    latlng={ lat: _lat, lng: _lng };

                    bounds = new google.maps.LatLngBounds();
                    infowin = new google.maps.InfoWindow();

                    /* invoke the map */
                    map = new google.maps.Map( document.getElementById('gmap'), {
                       center:latlng,
                       zoom: 15
                    });

                    /* show the initial marker */
                    marker = new google.maps.Marker({
                       position:latlng,
                       map: map,
                       title: 'Hello World!'
                    });
                    bounds.extend( marker.position );


                   $.ajaxSetup({
                        headers: {
                            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                        }
                    });

                    $.ajax({
                        type: 'GET',
                        url: '{{route("voyager.dashboard")}}',
                        data: {id:id},
                        success: function (response){

                           $.each(response, function( i,item ){
                                /* add a marker for each location in response data */ 
                                addMarker( item.latitude, item.longitude, item.location_status );
                            });
                        },
                        error: function(){
                            alert('There was an error loading the data.');

                        }
                    });                 
                }

                /* simple function just to add a new marker */
                function addMarker(lat,lng,title){
                    marker = new google.maps.Marker({/* Cast the returned data as floats using parseFloat() */
                       position:{ lat:parseFloat( lat ), lng:parseFloat( lng ) },
                       map:map,
                       title:title
                    });

                    google.maps.event.addListener( marker, 'click', function(event){
                        infowin.setContent(this.title);
                        infowin.open(map,this);
                        infowin.setPosition(this.position);
                    }.bind( marker ));

                    bounds.extend( marker.position );
                    map.fitBounds( bounds );
                }

                document.addEventListener( 'DOMContentLoaded', showMap, false );
            }());
        </script>

At ajax setting, when I put "dataType:json", function error executed. The output is alert "There was an error loading the data".

This is my controller :

 public function _index(Request $request)
    {
        $locations = Location::select('latitude','longitude','location_status')->get();

        if( $locations ) {
            foreach( $locations as $location ) {
                $markers[]=array( 'latitude'=>$location->latitude, 'longitude'=>$location->longitude, 'location_status'=>$location->location_status );
            }
            return json_encode($markers, JSON_FORCE_OBJECT);     
        }

        return view('vendor.voyager.index');

I tried console.log(response), it display whole javascript code.

Currently error without "dataType:'json'" shown "Uncaught TypeError: Cannot use 'in' operator to search for 'length'..."

I alreday tried this :

$.each(JSON.parse(response), function( i,item )

The error shown "Uncaught SyntaxError: Unexpected token < in JSON at position 0 at JSON.parse ()..."

This is route at api.php :

Route::group(['middleware' => ['api']], function () {
    Route::get('/', ['uses' => 'VoyagerController@_index',   'as' => 'voyager.dashboard']);
});

I'm not familiar with ajax/jQuery. It's my first time using it. Hope anyone can help me. Thank you in advance.

3
  • First try, under the declaration of $locations in your controller, add this line: return response()->json($locations);. You could also Get to Post, in the ajax call and in your route Route::post(/google_markers', 'VoyagerController@googleMarkers')->name('google.markers'), change your ajax url call to 'google.markers' too. Routing to '/' probably never gets you to the api call in the first place. So move your controller code to a public function googleMarkers. You don't use the id you send, but that's ok for now. Separate your code please. Commented Jun 24, 2019 at 2:59
  • It's worked! It took me a week to solve this issue. I changed the return at controller, then for route I changed method and name. But I still using '/' at route because the google map should display at my dashboard after user login, the url will be 127.0.0.1:8000/admin. I think route name "voyager.dashboard" is already defined by package of admin panel that I used. Thanks! Commented Jun 24, 2019 at 3:25
  • Nice to hear, so let me define a complete answer so you can declare it as correct. Commented Jun 24, 2019 at 3:28

1 Answer 1

1

Change your function to

public function googleMarkers(Request $request)
    {
        $locations = Location::select('latitude','longitude','location_status')->get();

        return response()->json($locations);
}

Your route to

Route::post('/', ['uses' => 'VoyagerController@googleMarkers',   'as' => 'gooogle.markers']);

And as a consequence, your ajax call to

$.ajax({
   type: 'POST',
   url: '{{route("google.markers")}}',
   data: {id:id},
Sign up to request clarification or add additional context in comments.

4 Comments

As a remark, you still don't use the send id and using '/' as the url route for your ajax request is risky business. It won't hurt a thing to change it to '/google_markers' as your ajax url call is dynamically set in the javascript.
Ok thanks! Btw, may I know why I can not use method GET?
In this case it can't, because of the base url of the request, being '/'. But any post request you will send to the / page will be treated as it were the google.markers ajax call. That's why you should give the Route anything but '/'. In ajax calls it is better to work with POST so it can never be mistaken for a http GET. And robots can not accidentally log ajax calls as HTTP requests. The only exception (maybe) is in a query search (...?q=my%20search%string) which can be logged by search engine robot.
Another reason that in a POST you know your data will arrive in one piece. In a GET all goes into the URL. For numeric values that is not a problem. But what about text? Or non UTF-8 characters? Simply put, with a POST you are sure that what you send you will receive. If decoded into an URL, this certainty falls away.

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.