How to save multiple lat long into database from multiple google places address textbox in laravel php. I have a dynamic textbox for google address


I have a dynamic textbox(add more) which shows Google places autosuggestion on each. I need to save every lat long from the address. I am getting the lat long but not able to get it in request for all those. I have a system to create polylines on the given addresses(working) but not able to save those lat long into db.

My Blade file

<div class="content-wrapper">
<div class="row">
    <div class="col-12 grid-margin">
        <div class="card">
          <div class="card-body">
            <h4 class="card-title">Schedule Job for <u>{{$shipment->shipment_number}}</u></h4>
            <p class="card-description">
              Fill up following details for Load assignment
            </p>
            <form class="form-sample" method="POST" action="{{route('job-schedules.store')}}">
                @csrf
                @method('POST')
              <p class="card-description">
                Add Stops <td><button type="button" name="add" id="dynamic-ar" class="btn btn-outline-primary btn-sm">Add More</button></td>
              </p>


                



              <div class="row">
                  <div class="col-md-4">
                  <div id="dynamicAddRemove">
                    <div class="input-group">
                        <input id="pac-input" name="endpoints[0][endpoint]" type="text" class="col-form-label-sm form-control address" placeholder="Enter location" />
                        <input type="hidden" name="endpoints[0][endpoint_lat]" id="endpoint_lat0" value="">
                        <input type="hidden" name="endpoints[0][endpoint_lng]" id="endpoint_lng0" value="">
                    </div><br>
                    <div class="input-group">
                        <input id="pac-input1" name="endpoints[1][endpoint]" type="text" class="col-form-label-sm form-control address" placeholder="Enter location" />
                        <input type="hidden" name="endpoints[1][endpoint_lat]" id="endpoint_lat1" value="">
                        <input type="hidden" name="endpoints[1][endpoint_lng]" id="endpoint_lng1" value="">
                    </div>
                </div>
                  <br>
                  <button type="submit" class="btn btn-outline-success btn-block">Save</button>
                  <a href="javascript:void(0)" id="set">Show route</a>
                  </div>
                  <div class="col-md-8">
                  
                    <div id="map" style="height: 540px;"></div>
                    <div id="maptest" style="height: 540px;" style="display:none;"></div>
                  </div>
                </div>
            </form>
          </div>
        </div>
      </div>
</div>

My Js

    <
script src = "https://polyfill.io/v3/polyfill.min.js?features=default" > < /script> <
    script src = "https://maps.googleapis.com/maps/api/js?key=mykey&callback=start&libraries=places&v=weekly"
async > < /script> <
    script type = "text/javascript"
src = "https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places" > < /script> <
    script type = "text/javascript" >
    const waypts = [];
var j = 1;
$("#dynamic-ar").click(function() {
    ++j;
    $("#dynamicAddRemove").append(`<br>
    <div class="input-group">
      <input id="pac-input` + j + `" name="endpoints[` + j + `][endpoint]" type="text" class="col-form-label-sm form-control address" placeholder="Enter a location" />
      <input type="hidden" name="endpoints[` + j + `][endpoint_lat]" id="endpoint_lat` + j + `" value="">
      <input type="hidden" name="endpoints[` + j + `][endpoint_lng]" id="endpoint_lng` + j + `" value="">
      <div class="input-group-append">
        <a class="remove-input-field" data-toggle="tooltip" title="Show" href="#"><i class="mdi mdi-delete"></i></a>
      </div>
    </div>`);
    var clone = document.getElementById('pac-input' + j);
    var ac = new google.maps.places.Autocomplete(clone);
    //apply listener
    google.maps.event.addListener(ac, 'place_changed', function() {
        var placeLocation = this.getPlace();
        var Lats = placeLocation.geometry.location.lat();
        var Lngs = placeLocation.geometry.location.lng();

        waypts.push({
            lat: Lats,
            lng: Lngs,
        });

    });
});
$(document).on('click', '.remove-input-field', function() {
    $(this).parents('div.input-group').remove();
}); <
/script>

<
script >
    var inputs = document.getElementsByClassName('address');
var autocompletes = [];

function initialize() {
    for (var i = 0; i < inputs.length; i++) {
        var autocomplete = new google.maps.places.Autocomplete(inputs[i]);
        autocomplete.inputId = inputs[i].id;

        autocomplete.addListener('place_changed', function() {
            var place = this.getPlace();
            var myLat = place.geometry.location.lat();
            var myLng = place.geometry.location.lng();
            waypts.push({
                lat: myLat,
                lng: myLng,
            });
        });
    }
}


function setInputValue(input_id, val) {
    document.getElementById(input_id).setAttribute('value', val);
} <
/script>


<
script >
    function initMap() {
        const map = new google.maps.Map(document.getElementById("map"), {
            zoom: 3,
            center: {
                lat: 0,
                lng: 0
            },
            mapTypeId: "terrain",
        });
        const flightPlanCoordinates = [
            waypts
        ];
        const lineSymbol = {
            path: google.maps.SymbolPath.FORWARD_CLOSED_ARROW,
        };
        const flightPath = new google.maps.Polyline({
            path: waypts,
            geodesic: true,
            strokeColor: "#4A89F3",
            strokeOpacity: 1.0,
            strokeWeight: 2,
            icons: [{
                icon: lineSymbol,
                offset: "100%",
            }, ],
        });
        var bounds = new google.maps.LatLngBounds();
        for (let i = 0; i < waypts.length; i++) {
            var point1 = new google.maps.LatLng(waypts[i]);
            bounds.extend(point1);
        }
        flightPath.setMap(map);
        map.fitBounds(bounds);
    }

google.maps.event.addDomListener(window, 'load', initialize);

$('#set').click(function() {
    initMap();
}); <
/script>

My Controller

public function store(Request $request)
{
    dd($request->endpoints);
    $input = $request->except(['_token']);
    $schedule = JobSchedule::create($input);
    foreach ($request->endpoints as $key => $value) {
        $value['job_schedule_id'] = $schedule->id;
        JobScheduleEndpoint::create($value);
    }
    return redirect()->route('customer.index')
        ->with('success','Customer added successfully.');
}

In model i have given lat long in fillable also


use IlluminateDatabaseEloquentFactoriesHasFactory;
use IlluminateDatabaseEloquentModel;
use AppModelsJobSchedule;

class JobScheduleEndpoint extends Model
{
    use HasFactory;

    protected $fillable = [
        'job_schedule_id',
        'endpoint',
        'endpoint_lat',
        'endpoint_lng',
        'status',
    ];

    public function job()
    {
        return $this->belongsTo(JobSchedule::class);
    }
}

Source: JavaSript – Stack Overflow

November 24, 2021
Category : News
Tags: google-maps | javascript | jquery | laravel | php

Leave a Reply

Your email address will not be published. Required fields are marked *

Sitemap | Terms | Privacy | Cookies | Advertising

Senior Software Developer

Creator of @LzoMedia I am a backend software developer based in London who likes beautiful code and has an adherence to standards & love's open-source.