Is it possible to identify if an array is a polygon or multipolygon by examining its GeoJson data?

Recently, I came across an example illustrating a simple polygon. However, I wanted to display countries with complex polygons (multipolygons for some countries). Let me demonstrate the process:

Example:

"type": "Feature",
    "properties": {
        "Name": "Country_with_multiple_polygons",
        "Description": ""
    },
    "geometry": {
        "type": "MultiPolygon",
        "coordinates": [
            [
                [-94.963194, 39.316858],
                [-94.959670, 39.321990],
                [-94.955570, 39.316610],
                [-94.963194, 39.316858]
            ],
            [
                [-35, 34],
                [-41, 37],
                [-43, 38],
                [-25, 39]
            ]
        ]
    }
}

var sector_data = {
    "type": "FeatureCollection",
    "features": [{
        "type": "Feature",
        "properties": {
            "Name": "Country_1",
            "Description": ""
        },
        "geometry": {
            "type": "Polygon",
            "coordinates": [
                [
                    [-94.963194, 39.316858],
                    [-94.959670, 39.321990],
                    [-94.955570, 39.316610],
                    [-94.963194, 39.316858]
                ]
            ]
        }
    }, {
        "type": "Feature",
        "properties": {
            "Name": "Country_2",
            "Description": ""
        },
        "geometry": {
            "type": "Polygon",
            "coordinates": [
                [
                    [-94, 36],
                    [-94, 35],
                    [-95, 34],
                    [-98, 32],
                    [-90, 31]
                ]
            ]
        }
    }]
};
var map;

function initialize() {
    var kansas_city = new google.maps.LatLng(39.00495613,-94.64780668);
    var mapOptions = {
        zoom: 10,
        center: kansas_city,
        mapTypeId: google.maps.MapTypeId.TERRAIN
    };
    map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
    sector_callback(sector_data);
}

// Loop through the results array and place a marker for each set of coordinates.
window.sector_callback = function(results) {
    var bounds = new google.maps.LatLngBounds();
    for (var i = 0, len = results.features.length; i < len; i++) {
        var coords = results.features[i].geometry.coordinates[0];
        var path = [];
        document.getElementById('coords').innerHTML += "Polygon "+i+"<br>";
        for ( var j = 0; j < coords.length; j++ ){
            // alert("coords["+j+"][1]="+coords[j][1]+", coords["+j+"][0]="+coords[j][0]);
            var pt = new google.maps.LatLng(coords[j][1], coords[j][0])
            bounds.extend(pt);
            path.push(pt);
            document.getElementById('coords').innerHTML += coords[j]+"<br>";
        }

        var polygons = new google.maps.Polygon({
          path: path,
                         strokeColor: "#FF0000",
                         strokeOpacity: 0.8,
                         strokeWeight: 1,
                         fillColor: "#FF0000",
                         fillOpacity: 0.35,
          map: map
        });
    }
    map.fitBounds(bounds);
}

Answer №1

Here is my personal answer for those in need:

Extracted data from a JavaScript file:

var sector_data = {
    "type": "FeatureCollection",
    "features": [
{
"type": "Feature",
"properties":{"Name": "Bolivia","Description": "-","Color":"#ff9900"},
"geometry":{"type": "Polygon","coordinates":

[

[
[-58.159,-20.164], ... [-65.313,-10.253], ... [-58.159,-20.164]
]

]
}// end geometry
}// end country
 // using "," 

,

{
"type": "Feature",
"properties":{"Name": "Cuba","Description": "-","Color":"#552233"},
"geometry":{"type": "Polygon","coordinates":

[



[
[-82.561,21.5716], ... , [-82.561,21.5716]
]
,
[
[-77.669,21.9519], ... , [-77.669,21.9519]
]
,
[
MORE POLYGONS
]

]
}// end geometry
}// end country
 // usage of ","



    ]
}; // END. PLEASE REMOVE '//' AND THE REST...



var map;

function initialize() {
    var latinoamerica = new google.maps.LatLng(-5,-63);
    var mapOptions = {
        zoom: 10,
        center: latinoamerica,
        mapTypeId: google.maps.MapTypeId.HYBRID,
        panControl: true,
        panControlOptions: {
        position: google.maps.ControlPosition.LEFT_TOP
        },
        zoomControl: true,
        zoomControlOptions: {
        style: google.maps.ZoomControlStyle.LARGE,
        position: google.maps.ControlPosition.LEFT_TOP
    },
    scaleControl: true,
    streetViewControl: false,
    };
    map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
    sector_callback(sector_data);
}

  // Iterate through the results array and add markers for each set of coordinates.
window.sector_callback = function(results) {
var bounds = new google.maps.LatLngBounds();
for (var i = 0, len = results.features.length; i < len; i++) {
//console.log(i)
//document.getElementById('coords').innerHTML += "Polygon "+results.features[i].properties.Name+"<br>";
Color = results.features[i].properties.Color
cualpais = results.features[i].properties.Name
//console.log(nombre)
for (var a=0;a < results.features[i].geometry.coordinates.length; a++ ){
var coords = results.features[i].geometry.coordinates[a];
//console.log(a)
var path = [];
    for ( var j = 0; j < coords.length; j++ ){
    // alert("coords["+j+"][1]="+coords[j][1]+", coords["+j+"][0]="+coords[j][0]);
    var nombre = new google.maps.LatLng(coords[j][1], coords[j][0])
    bounds.extend(nombre);
    path.push(nombre);
    //document.getElementById('coords').innerHTML += coords[j]+"<br>";
    }
    var nombre = new google.maps.Polygon({
      path: path,
      strokeColor: "#f5f5f5",
      strokeOpacity: 0.6,
      strokeWeight: 1,
      fillColor: Color,
      fillOpacity: 0.35,
      clickable: true,
      //map: map
     //console.log(map)
     // console.log(nombre)
    });
    nombre.setMap(map);


}
    map.fitBounds(bounds);
}}

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

Show the dropdown menu with names from the array in the ajax response

<html> <select name="cars"> <option value="34">Volvo XC90</option> <option value="54">Saab 95</option> <option value="12">Mercedes SLK</option> <option value="10">Audi TT</option> </select> ...

Load content within the DIV container

I need help finding code that can use JQuery to load a page into a DIV element. Essentially, I want to load displaycatch.php into a specific DIV <div id="results">Content for id "results" Goes Here</div> Furthermore, I would like to add a ...

Creating a conditional query in Mongoose: A step-by-step guide

The code below functions without any query strings or with just one query string. For example, simply navigating to /characters will display all characters. However, if you specify a query string parameter like /characters?gender=male, it will only show ma ...

Rendering nested routes in Vue router with the parent component

I attempted to nest my routes using Vue router, but encountered some difficulties { path: '/admin', name: 'Admin', component: () => import('pages/Admin'), children:[ { path: 'stock', name: ' ...

Can you explain the distinction between utilizing Object.create(BaseObject) and incorporating util.inherits(MyObject, BaseObject)?

Can you explain the difference between these two methods of setting the prototype? MyObject.prototype = Object.create(EventEmitter.prototype); MyObject.prototype = util.inherits(MyObject, EventEmitter); UPDATE I've noticed in various projects that ...

challenges encountered when saving a getjson request as a variable

I am experiencing difficulties in retrieving a variable from a getJSON() request. The issue lies within the following three functions: function getPcLatitude() { // onchange var funcid = "get_postcode_latitude"; var postcode = parseInt($('#i ...

How can we have a div stay at the top of the screen when scrolling down, but return to its original position when scrolling back up?

By utilizing this code, a div with position: absolute (top: 46px) on a page will become fixed to the top of the page (top: 0px) once the user scrolls to a certain point (the distance from the div to the top of the page). $(window).scroll(function (e) { ...

Cannot access jquery within an angular directive

I've been attempting to incorporate jquery-ui's sortable feature on the elements within an ng-repeat loop. The issue I'm facing is that I am unable to actually perform the sortable action on these ng-repeat elements. I have searched for so ...

Forward ReactJS

https://i.stack.imgur.com/r0IAE.pngI'm having trouble implementing a redirect to a submit confirmation page after pressing the submit button on my form. The backend server is set up to send an email upon submission, but adding an href to the button pr ...

An issue arises with React hooks: useMemo and useEffect display a Missing dependency error when attempting to invoke a function

triggerData function is being utilized in multiple functions. However, if I place the function inside the useEffect to prevent missing dependencies, then I am unable to call the triggerData outside of the useEffect i.e., in buildData. How can I resolve the ...

Incorporating items into a dynamic array using MobX

Issue with Pushing MobX Objects to an Observable Array I'm facing a challenge when trying to push objects into an observable array in MobX and iterate over them successfully. At the starting point, I initialize the observable array: if (!self.selec ...

The depth buffer in Webgl FrameBuffer is not being cleared properly

Currently, I am working on developing a 2D sprite renderer that utilizes render textures for custom compositing. However, I have encountered an issue where the depth buffer on the FrameBuffer is not clearing properly. Due to this, all the sprites leave a p ...

How to emphasize a portion of an expression in AngularJS using bold formatting

I have a specific goal in mind: to emphasize part of an angular expression by making it bold. To achieve this, I am working with an object obj which needs to be converted into a string str. obj = $scope.gridOptions1.api.getFilterModel(); for (var pr ...

Tips for identifying a webpage and making class modifications based on it

I am working on a customized bar with 4 distinct parts. Each part corresponds to a different page on the website. I want each part of the bar to change color based on which page the user is currently browsing. For example, if the user is on page A, I want ...

Identifying sluggish GPU performance on a mobile device using three.js: A guide for developers

My game runs extremely slow on older mobile devices like the Samsung Galaxy S4 and iPhone 5 when shadows are enabled. However, when shadows are turned off, performance improves significantly. Is there a way to detect a slow GPU in order to disable sh ...

Is Jquery "resistant" to updating CSS properties?

Within my HTML document, there exists a div with the class fd-video-upload-box, which has the following style properties applied: background-color: rgb(236, 238, 239); outline: 1px dashed gray !important; Upon rendering, it displays correctly as intended ...

What is the best way to pass a value back to the main function from an async.eachOfSeries function?

Currently, I am utilizing the async npm library in my project. I am interested in finding a way to return the value of 'someVar' back to the main function. The documentation indicates that it returns a promise if a callback is not provided. Howe ...

What is the best way to rearrange an array in React?

I need help with manipulating an array of strings displayed in a list. Each string should have the ability to move up or down within the array. For example: const array = ["hello", "world", "cool"] moveUp("world", 1) // (moveUp: value:string, index: nu ...

Creating an interactive time selection tool with two dropdown lists that are dependent on each other using HTML and JavaScript

Hi everyone, I am new to JavaScript. I am currently working on creating two dropdown lists, one for 'Start Time' and another for 'End Time'. These dropdown lists will display hours in a 24-hour format with intervals of 30 minutes. In t ...

The React-Chartjs chart is displaying without any color rendering

I attempted to create a radar chart using react-chartjs library, but I am facing an issue where the colors are not appearing when it renders. https://i.stack.imgur.com/tjAsW.png What could be causing this problem? I followed a significant portion of the ...