Skip to content
Advertisement

Posting Coordinates to Database from Google Maps API

Edit: I solved the problem. Leaving it up in case someone needs something similar in the future.

I am trying to use google map api to get coordinates and save the information in a database. If the user drags the marker then a form is updated with the information. User can also enter the information manually in the form if she wants and the map will be updated with a new marker. Then the user can click submit and the information will be saved in the database.

<form action="{{ route('YOUR_ROUTE') }}" method="post" enctype="multipart/form-data">

<div class="form-group">

<div style="padding-top: 10px;">
                                <div id="map-location"></div>
                            </div>

{{--                            visibility, lat, lng, location --}}

                                <input class="form-control" type="text" name="location_name" id="location_name" placeholder="Location">

                                <input class="form-control" type="text" name="latitude" id="latitude" placeholder="Latitude" style="max-width: 50%;">

                                <input class="form-control" type="text" name="longitude" id="longitude" placeholder="Longitude" style="max-width: 50%;">


                        <button type="submit" class="btn btn-primary">Post</button>
                        <input type="hidden" value="{{ Session::token() }}" name="_token">
                        
                        </div>
                    </form>
                    
                    
                    
<script>
        //initialise and add the map
        function initMap(){
//    location of midtown manhattan
            var midtown = {lat: 40.7549, lng: -73.9840};
//    the maps centered at midtown
            var map = new google.maps.Map(document.getElementById('map-location'),{zoom:17, center:midtown});
//    the marker
            var marker = new google.maps.Marker({position: midtown, map: map, draggable: true});

            infoWindow = new google.maps.InfoWindow;

            // Try HTML5 geolocation.
            if (navigator.geolocation) {
                navigator.geolocation.getCurrentPosition(function(position) {
                    var pos = {
                        lat: position.coords.latitude,
                        lng: position.coords.longitude
                    };

                    marker.setPosition(pos);

                    map.setCenter(pos);
                }, function() {
                    handleLocationError(true, infoWindow, map.getCenter());
                });
            } else {
                // Browser doesn't support Geolocation
                handleLocationError(false, infoWindow, map.getCenter());
            }

        function handleLocationError(browserHasGeolocation, infoWindow, pos) {
            infoWindow.setPosition(pos);
            infoWindow.setContent(browserHasGeolocation ?
                'Error: The Geolocation service failed.' :
                'Error: Your browser doesn't support geolocation.');
            infoWindow.open(map);
        }

            //    dragged event of the marker
            google.maps.event.addListener(marker, 'dragend', function(){
                var lat = marker.getPosition().lat();
                var lng = marker.getPosition().lng();
                var address;

                $('#latitude').val(lat);
                $('#longitude').val(lng);

                var geocoder = new google.maps.Geocoder();
                geocoder.geocode({latLng: marker.getPosition()}, function(result,status){
                    if(status == google.maps.GeocoderStatus.OK){
                        address = result[0].formatted_address;
                        // console.log(address);
                        $('#location_name').val(address);
                    }
                    else{
                        console.log('Geocode was not successful for the following reason: ' + status);
                    }
                });
            });

        //    when the place is changed in the location box the map updates
            searchBox = new google.maps.places.SearchBox(document.querySelector( '#location_name' ));

            google.maps.event.addListener(searchBox, 'places_changed', function(){
                var places = searchBox.getPlaces(),
                bounds = new google.maps.LatLngBounds();

                for(var i = 0; place = places[i]; i++){
                    bounds.extend(place.geometry.location);
                    marker.setPosition(place.geometry.location);
                }

                map.fitBounds(bounds);
                map.setZoom(15);

                var lat = marker.getPosition().lat();
                var lng = marker.getPosition().lng();

                $('#latitude').val(lat);
                $('#longitude').val(lng);
            });
        }
    </script>
    <script async defer src="https://maps.googleapis.com/maps/api/js?key=YOUR_KEY&libraries=places&callback=initMap"></script>

Advertisement

Answer

I updated my first post with the code that is working for me.

I couldn’t update the map with the information from the form because I didn’t include the places library while loading the Maps JavaScript API.

I couldn’t see the updated coordinates after dragging the map marker because I didn’t enable the geocoding api and didn’t create a billing account with google cloud. I also restricted my API key.

Hope this helps.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement