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

Enhancing the appearance of individual cells within an HTML table by applying custom classes

I'm in the process of automating report generation for my organization. Our workflow involves using R to summarize data from Excel, then utilizing Rmarkdown, knitr, and the "htmlTable" package to generate HTML files. Currently, I am implementing CSS ...

Looping over the results of JSON.Parse() in Ruby on Rails can be done

I am new to using Rails but I am really enjoying it. However, I have encountered a problem that I can't seem to solve. Most of the solutions I find online are related to ActiveRecord objects, but my issue involves working with JSON data from a RESTful ...

Receive regular updates every week for an entire month using Javascript

How can I calculate the number of check-ins per week in a month using Javascript? I have been unable to find relevant code for this task. Specifically, I am interested in determining the total count of user check-ins on a weekly basis. For example, if a u ...

Select a checkbox automatically after receiving an ajax response

I am currently working with a form that contains multiple checkboxes like the one below: <label class="checkbox"> <input type="checkbox" id="user_ids_for_edit" name="user_ids_for_edit[]" data-toggle="checkbox" data-toggle="checkbox" value="14"&g ...

AngularJS substitution with regular expressions

Looking to replace specific words in HTML content within <div> and <p> tags upon page load. Utilizing angularJS to achieve this task. This is my current function: var elementsList = e.find('p'); var regex = ('[^<>\& ...

What is the process for exporting a plugin from dayjs() in JavaScript?

Currently, I have incorporated the plugin isToday() to enhance the capabilities of dayjs(). Nevertheless, I am uncertain about how to export isToday() in order to utilize it across other files. import isToday from "dayjs/plugin/isToday"; expor ...

a guide to transforming data into a string with json using angular

I am struggling to figure out how to bind my form data into a JSON string. My situation involves using a string field in the database and saving checkbox values in a single database column using JSON. I have created an HTML form, but I am unsure of how to ...

Cleaning up checkbox names by removing unnecessary characters

I'm having an issue with unnecessary characters in the names of checkboxes. There is a certain line var string = "<div class="blblb"><input type="checkbox" name="dasdasads"><input type="checbox" name="adsdsada"></div>"; The ...

ReactJS Error: Rendering objects as a React child is not supported. If you intended to render multiple children, make sure to use an array instead

customMovieService.js: const films = [ { _id: "5b21ca3eeb7f6fbccd471815", title: "Inception", genre: { _id: "5b21ca3eeb7f6fbccd471818", name: "Sci-Fi" }, numberInStock: 8, dailyRentalRate: 2.0, publishDate: "2019-07-15T14:36:40.8 ...

Guide to dynamically implementing pagination through AJAX calls

In this javascript code snippet, I have a class named PurchaseHistory. var baseUrl = null; var parameters = null; var currentPageNumber = null; var TotalPages = null; var PageSize = null; $(document).ready(function () { baseUrl = "http://localhost/AP ...

Having trouble getting Vue.js data to show up on the screen. I'm attempting to show a list of todos, but all that

I'm currently working on my App.vue file where I have set up the data for a todo list. However, despite creating an array of todos and attempting to display them, nothing is showing up on the screen. I'm at a standstill and could really use some ...

Webhook notifications from Facebook's Graph API feed

After subscribing to the feed in the graph api webhook, I have noticed that I am consistently receiving updates to my callback URL. However, the problem arises when I receive updates for every single action that occurs on the posts such as likes and commen ...

What is causing my button to act in this way?

Initially, the website redirects to an undefined URL and then to test.com. I am looking for a way to implement a redirection sequence from to and finally to <head> <script type="text/javascript"> <!-- function popup(url ...

Currently dealing with a script that utilizes AJAX GET to incorporate JSON data into my table

Greetings and thank you for taking the time to read this! Within my HTML, I have implemented a form element that allows inputting data into 5 different fields. This data is then transmitted to a database using my unique API key. Once stored in the database ...

Optimal method for conducting Jasmine tests on JavaScript user interfaces

After exploring the jasmine framework for the first time, I found it to be quite promising. However, I struggled to find a simple way to interact with the DOM. I wanted to be able to simulate user interactions such as filling out an input field, clicking ...

Show the subscription response data in Angular

When utilizing the code snippets below from two different components, I am able to receive a valid response value from the subscriber. dataService.ts fetchFormData(){ return this.http.get('http://localhost:48116/RecuruitmentService.asmx/addRoleTest ...

Which callback function is best suited for handling the response in an XMLHttpRequest and rendering it on the webpage?

Upon a user action on the page, an AJAX request is made to my Node.js Express server to send data. Here's what happens next: router.post('/', function(req, res){ //user authentication first, then inside that callback res.redirect('/d ...

Making sure to detect page refresh or closure using jQuery or JavaScript

Could there be a way to determine if a page has been refreshed or closed using jQuery or javascript? The current scenario involves having certain database values that need to be deleted if the user either refreshes or leaves the page. AJAX calls are bein ...

Daniel Opitz explores the best placement for DataTables within the slim4 framework

After purchasing Daniel Opitz's eBooks, I found myself on page 226 trying to implement data tables in my project. The books mention: DataTables Setup DataTables.net is a very flexible table plug-in for jQuery. You have to setup jQuery for Webpack firs ...

Is there a more efficient alternative to the sluggish scroll event?

Currently, I have set up a scroll event that tracks the user's position on the page and updates the navigation styling based on which section they are viewing. However, the calculation I'm using during scrolling is quite resource-intensive and ca ...