0
votes

I'm having an issue with trying to add an AJAX request to a google map as the title suggests. My web app currently allows a user to search a location which will return a marker to that location as well as the longitude and latitude of the location.

Screenshot of Map

Essentially what I'm trying to do is pass the latitude and longitude variables calculated into a controller class in Spring MVC, and I'm attempting to do this via an AJAX request, however when I add the AJAX request to a JS function, and add this function to the onClick() of the "Locate" button the map disappears and the search functionality no longer works.

Screenshot of empty map

Is this happening because I'm reusing the $('.search_latitude').val(), and Long : $('.search_longitude').val() variables and the program is getting confused as to what I'm trying to do, or is it a case of my approach to the AJAX request is wrong?

Google Map JS code

 <script>
    var geocoder;
    var map;
    var marker;

    /*
     * Google Map with marker
     */
    function initialize() {
        var initialLat = $('.search_latitude').val();
        var initialLong = $('.search_longitude').val();
        initialLat = initialLat?initialLat:53.350140;
        initialLong = initialLong?initialLong:-6.266155;

        var latlng = new google.maps.LatLng(initialLat, initialLong);
        var options = {
            zoom: 11,
            center: latlng,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };

        map = new google.maps.Map(document.getElementById("geomap"), options);

        geocoder = new google.maps.Geocoder();

        marker = new google.maps.Marker({
            map: map,
            draggable: true,
            position: latlng
        });

        google.maps.event.addListener(marker, "dragend", function () {
            var point = marker.getPosition();
            map.panTo(point);
            geocoder.geocode({'latLng': marker.getPosition()}, function (results, status) {
                if (status == google.maps.GeocoderStatus.OK) {
                    map.setCenter(results[0].geometry.location);
                    marker.setPosition(results[0].geometry.location);
                    $('.search_addr').val(results[0].formatted_address);
                    $('.search_latitude').val(marker.getPosition().lat());
                    $('.search_longitude').val(marker.getPosition().lng());
                }
            });
        });

    }

    $(document).ready(function () {
        //load google map
        initialize();

        /*
         * autocomplete location search
         */
        var PostCodeid = '#search_location';
        $(function () {
            $(PostCodeid).autocomplete({
                source: function (request, response) {
                    geocoder.geocode({
                        'address': request.term
                    }, function (results, status) {
                        response($.map(results, function (item) {
                            return {
                                label: item.formatted_address,
                                value: item.formatted_address,
                                lat: item.geometry.location.lat(),
                                lon: item.geometry.location.lng()
                            };
                        }));
                    });
                },
                select: function (event, ui) {
                    $('.search_addr').val(ui.item.value);
                    $('.search_latitude').val(ui.item.lat);
                    $('.search_longitude').val(ui.item.lon);
                    var latlng = new google.maps.LatLng(ui.item.lat, ui.item.lon);
                    marker.setPosition(latlng);
                    initialize();
                }

            });
        });

        /*
         * Point location on google map
         */
        $('.get_map').click(function (e) {
            var address = $(PostCodeid).val();
            geocoder.geocode({'address': address}, function (results, status) {
                if (status == google.maps.GeocoderStatus.OK) {
                    map.setCenter(results[0].geometry.location);
                    marker.setPosition(results[0].geometry.location);
                    $('.search_addr').val(results[0].formatted_address);
                    $('.search_latitude').val(marker.getPosition().lat());
                    $('.search_longitude').val(marker.getPosition().lng());
                } else {
                    alert("Geocode was not successful for the following reason: " + status);
                }
            });
            e.preventDefault();
        });

        //Add listener to marker for reverse geocoding
        google.maps.event.addListener(marker, 'drag', function () {
            geocoder.geocode({'latLng': marker.getPosition()}, function (results, status) {
                if (status == google.maps.GeocoderStatus.OK) {
                    if (results[0]) {
                        $('.search_addr').val(results[0].formatted_address);
                        $('.search_latitude').val(marker.getPosition().lat());
                        $('.search_longitude').val(marker.getPosition().lng());
                    }
                }
            });
        });
    });

    geocoder.geocode({
        'address': request.term,
        componentRestrictions: {country: "ie"}
    })

    function loginAlert(){
        alert("User must be logged in to view reports");
    }

     *************JS Function with the AJAX Request*************************    
     function sendLatLong(){

        var Lat = $('.search_latitude').val();
        var Long = $('.search_longitude').val(); 

        $.ajax({
               type: "POST",
               url: "/latlong",
               data: {
                       Lat : $('.search_latitude').val(),
                       Long : $('.search_longitude').val()
               })
    } 

    </script>
    </head>
    <body>

    <h3>Area Rating System</h3>

    //Some code omitted for brevity

    <form>
    <div class="form-group input-group">
        <input type="text" id="search_location" class="form-control" placeholder="Search location"/>
        <div class="input-group-btn">
            <button class="btn btn-default get_map" type="submit" onClick() = "sendLatLong()">
                Locate
            </button>
        </div>
    </div>
    </form>

    <!-- display google map -->
    <div id="geomap"></div>

    <div id="forminputs">
    <table>
    <tr>
    <!-- display selected location information -->
    <th>
    <h4>Location Details</h4>
    <p>Address: &nbsp; &nbsp;<input type="text" class="search_addr" size="45"/></p>
    <p>Latitude: &nbsp; &nbsp;<input type="text" class="search_latitude" size="30"/></p>
    <p>Longitude: <input type="text" class="search_longitude" size="30"/></p>
    <p style = "height: 120px"></p>

AJAX code snippet from the Google Map code above (included and highlighted above as well)

function sendLatLong(){

    var Lat = $('.search_latitude').val();
    var Long = $('.search_longitude').val(); 

    $.ajax({
           type: "POST",
           url: "/latlong",
           data: {
                   Lat : $('.search_latitude').val(),
                   Long : $('.search_longitude').val()
           })
} 

Server-side code in the controller class

@RequestMapping(value = "/latlong", method = RequestMethod.POST)
public @ResponseBody
String Submit(@RequestParam("Lat") String latitude,@RequestParam("Long") String longitude) {
    // your logic here
    System.out.println(latitude + "" + longitude);
    return null; //I just want to print the latitude and longitude for now to show it has been sent to the serverside
}
1

1 Answers

0
votes

I see that your button is inside a form and has a type as 'submit'.

type="submit"

This might be reloading the page and hence the map gets disappeared.

To make this request as completely asynchronous, the best possible solution would be to make the button as of type 'button'

type="button"

This will ensure that the form does not submits and you handle the submission using the AJAX 'submit' call.

Do that change and tell me in comments if the problem is still there. I'm just guessing it based on limited information.

It would also be helpful if you could share the console error log snippet along with this. Maybe that can also help.