Uploading a KML file and displaying the coordinates on a Leaflet map.
In this article I will be guiding you how to load a KML file onto a leaflet map. Using this newly added layer from the KML file, this data can be saved to the database using the approach I have laid out in one of my previous articles.
For this example, I will be using Leaflet Omnivore, which is an addon to leaflet which allows the conversion between file types such as KML. The theory behind this is that the KML file gets uploaded and saved to the public folder and then the path is returned back to the same blade file using Ajax. The path is inserted into the function and the coordinates in that KML file will be added as a layer to the map and displayed to the user.
The code for the blade file
There is an upload button which will submit the form and activate the onsubmit function. That basically saves the kml file with a random name. Then we fetch the path of the saved file and we create a KML overlay and add that overlay as a layer to the leaflet map.
The route
Route::post('/ajax_upload/action', [UserController::class, 'action'])->name('ajaxupload.action');
The controller
function action(Request $request){$validation = Validator::make($request->all(), ['select_file' => 'required']);if($validation->passes()){$kml= $request->file('select_file');$new_name = rand() . '.' . $kml->getClientOriginalExtension();$kml->move(public_path('kml'), $new_name);return response()->json(['message' => 'File Uploaded Successfully','uploaded_file' => "kml/$new_name",'class_name' => 'alert-success']);}else{return response()->json(['message' => $validation->errors()->all(),'uploaded_file' => '','class_name' => 'alert-danger']);}}
And that should load your uploaded KML file’s coordinates onto your map.