Trouble arises when implementing MultiLineString functionality within LeafletGIS

After receiving a response from the server, I found that I needed to restructure it to fit the GeoJSON standard in order to use it for marker animation in Leaflet. The coordinates also needed to be flipped, as Leaflet uses lat, lng while my data was in lng, lat format from Geoserver.

Here is a good reference for the GeoJSON standard, and the datatype I require is MultiLineString, as shown on page 24.

UPDATED:

I was able to get the proper JSON structure for MultiLineString,

[[[lat,lng],[lat,lng]], [lat,lng],[lat,lng]]...
, as seen in the first image.

However, when using the restructured variable (flippedCoords) to create a polyline and animate a marker over it, I encountered bugs. The console did not show any errors, but other layers started behaving strangely as soon as the response was loaded and I zoomed in/out.

Here is the ajax call and attempt to structure the response:

function getFinalRoute(){
var urlRoute = `${geoserver}/wfs?service=WFS&version=1.0.0&request=GetFeature&
typeName=xxx:shortestpath&viewparams=source:${source};target:${targetN || targetE}&outputformat=application/json
&srsName=EPSG:4326`;
var routeLayer = L.geoJSON(null);
var flippedCoords;
$.ajax({
    url: urlRoute,
    async: false,
    success: function(response){
                var routeArr = response.features;
                var coordsArr = Object.keys(routeArr).map(key => {
                    return routeArr[key]
                })
                    var xxy = coordsArr.map(function(feature){
                    var obj = feature.geometry.coordinates[0];
                    return Object.keys(obj).map(function(key){
                        return obj[key];                        
                    })
                })

                
                var flipCoor = L.GeoJSON.coordsToLatLngs(xxy, 1);
                flippedCoords = flipCoor.map(function(obj){
                    return Object.values(obj).map(function(obj){
                        return Object.values(obj)
                        })
                    })
//code below is from Animate marker plugin and works fine with linestring           
                var multiLineString =  L.polyline(flippedCoords); 
                var secondAnimated = L.animatedMarker(multiLineString.getLatLngs(), {
                                        distance: 10,
                                        interval: 2000,
                                        iconSize:[16,16],
                                        iconAnchor: [7, 16],
                                        //autostart: false,
                                        icon: pulsingIcon
                                                        
                                    });

                routeLayer = L.geoJSON(response);   
                map.addLayer(secondAnimated);
    }   
    
});     

    map.addLayer(routeLayer);       

};

Answer №1

In order to ensure everything runs smoothly, you can initialize an empty_arr global object. Below is an example of how you can achieve this:

var empty_arr = new Array();
success: function(response){
    var routeArr = response.features;
    routeArr.forEach(linePart => { 
        var coords = linePart.geometry.coordinates;
        coords.forEach(function(coord){
            var newArray = coord;
            var finalArr = newArray.map(function(obj){
                return Object.values(obj).sort().map((value)=>{
                    return value
                })
            })
            var flipCoor = L.GeoJSON.coordsToLatLngs(finalArr, 0);
            var flippedCoor = flipCoor.map(function(obj){
                return Object.keys(obj).sort().map(function(key){
                    return obj[key];
                })
            })
            
            empty_arr.push(flippedCoor);...

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Developers specializing in Google Maps navigate to a particular destination

I have been working on an app that provides users with the best options for places to visit, utilizing Google Maps technology. Here is what I have accomplished so far: Show the user their current location Show the user possible destinations (with marker ...

What is the functionality of this.$eval in Vue.js?

During the process of updating an unfamiliar old script from version 0.11 to 2.5.4, an alert popped up stating: To address the warning message saying 'Replace this.$eval('reportData | reportFilter false') with a solution using normal Java ...

Presentation - hyperlink only functioning for final slide

I have a question about Lean Slider, which you can check out at My goal is to link each slide to a different URL. However, I'm facing an issue where only the code in the last slide seems to be executed and applied to all other slides. For example, if ...

Toggle the visibility of a div based on whether or not certain fields have been filled

Having a form with a repeater field... <table class="dokan-table"> <tfoot> <tr> <th colspan="3"> <?php $file = [ 'file' => ...

What is the best way to align geometry at the bottom of the screen in Three.js while still preserving its aspect

I recently started using Threejs and encountered an issue with positioning geometry. I'm trying to place the geometry at the bottom with half of it cut off, so only half should be visible. However, when I use position.setY(-300), the geometry moves do ...

Requests in Node.js may unexpectedly stall and remain unresolved until the server is restarted

I've encountered a strange and seemingly sporadic issue with our web application that I can't seem to resolve through debugging. The app runs smoothly for varying durations, ranging from 10 minutes to 6 hours, but then all of a sudden, any remote ...

Retrieving the value of the selected item when it is changed

I am currently using v-select/v-autocomplete in my project: <v-autocomplete v-modal="newRole" :items="roles" label="--Change role--" required return-object item-value="id" item-text=&qu ...

Randomly undefined custom jQuery function

Appreciate your assistance in advance. I am facing a peculiar scope issue on a page where multiple charts are rendered intermittently. I have created a set of jQuery functions to display different types of charts based on the provided options. Each funct ...

Activate event starting from parent and ascending through child nodes

When I have a table inside a <div class="timely"></div>, and within that table is a <th class="prev"><i>previous</i></th>, Chrome developer tools show an event listener on the <th>. However, Firefox developer tools ...

Setting up Spectron

I attempted to install Spectron using the following command: npm install --save-dev spectron However, I encountered the following error message: npm ERR! Windows_NT 6.1.7601 npm ERR! argv "C:\Program Files\nodejs\node.exe" "C:\P ...

Utilize React Material UI to elegantly envelop your TableRows

Currently, I am faced with a challenge involving a table that utilizes Material UI and React-table. My goal is to wrap text within the TableRow element, but all my attempts have not been successful so far. Is there anyone who knows the best approach to a ...

Navigating in React: How to Implement the Same Route for Different Scenarios Without Compromising Your Application

I'm facing a frustrating issue while trying to incorporate Redux state management and React Router. Despite searching extensively online, I can't seem to find a solution. My Redux state, named user, stores the details of a logged-in user. Upon l ...

Accessing XML data using Cross-Domain AJAX

New to this! I'm currently working on a client script that requires reading an XML file from another domain. I attempted to utilize JSONP, and while I receive a 200 response, the client is unable to access the data returned for some unknown reason. Tw ...

Filtering rows of an HTML table that contain links in the `<href>` column data in real time

When using HTML and JavaScript, I have found a solution that works well for many of the columns I am working with. You can see the details on how to dynamically filter rows of an HTML table using JavaScript here. var filters=['hide_broj_pu',&apo ...

Can data be transferred within a callback to the function it encapsulates?

I am currently working on developing a user login system and I find myself in need of querying the database. Being a beginner in coding, I am grappling with the concept of callbacks and how data can be passed once the callback has been executed. My dilemm ...

Is there a way to only refresh the div specifically for the calendar with an id of "

$(document).ready(function() { $("#client-list").on("change", function() { var selectedValue = $(this).val(); location.reload(); }); }); Is there a way to refresh only the div with id='calendar' without refreshing the entire pa ...

Ways to make a component gradually appear and disappear in an Angular application

I have developed a task management application using Angular and I wanted to implement a fading effect for each task when it is created and before it is deleted. Despite successfully applying the fade in effect at the todo-item component level, I encounter ...

What is the best way to trigger a child function from the parent component in React?

In my React application, there are three components: two child components and one parent component. I need to pass data (projectId) from ChildOne to ChildTwo through the Parent component and trigger a function once the data is received. Essentially, I am s ...

Is there a way to retrieve YouTube URLs through programming automation?

I'm currently working on a project to automatically retrieve YouTube URLs and incorporate a download button feature. I found a tutorial suggesting the use of 'ytplayer.config.args.url_encoded_fmt_stream.map.split(",");' After attempting to ...

The transition between backgrounds is malfunctioning

I want to create a smooth transition effect for changing the background of an element within a setInterval function. Currently, the background changes immediately, but I would like it to transition over a period of time. var act = true; setInterval(func ...