Incorporating external API information into Google Maps

My current challenge involves creating a polygon on Google Maps using data obtained from an external API found at .

Upon analyzing the API response, the following information is provided:

{
"id": 28,
"name": "Local spots",
"description": "",
"isprivate": true,
"status": "active",
"created_at": "2014-09-15T09:40:01.747Z",
"geographic_extent": {
    "type": "Polygon",
    "coordinates": [
        [
            [-0.508, 51.682],
            [-0.53, 51.327],
            [0.225, 51.323],
            [0.167, 51.667],
            [-0.508, 51.682]
        ]
    ]
}, 

I am seeking assistance in extracting the coordinates under 'geographic_extent' and displaying them as a polygon on the Google Map. I believe an AJAX call is necessary, but how do I extract this specific data when the entire array would be returned?

Your help would be greatly appreciated.

Thank you.

Below is the script used to generate the map:

var map;

function initMap() {
    map = new google.maps.Map(document.getElementById('map'), {
    zoom: 2,
    center: new google.maps.LatLng(2.8,-187.3),
});
}

Answer №1

To retrieve the 'geographic_extent' element from the AJAX response that is received, you can utilize the JSON.parse method. Example:

var result = JSON.parse('{"id": 28,"name": "Local spots","description": "","isprivate": true,"status": "active","created_at": "2014-09-15T09:40:01.747Z","geographic_extent": {"type": "Polygon",    "coordinates": [[[-0.508, 51.682],[-0.53, 51.327],[0.225, 51.323],[0.167, 51.667],[-0.508, 51.682]]]}');

now you can obtain

-0.508,51.682,-0.53,51.327,0.225,51.323,0.167,51.667,-0.508,51.682

using

result.geographic_extent.coordinates

If you wish to display it as a polygon, use the following script

var triangleCoords = [
          {lat: 25.774, lng: -80.190},
          {lat: 18.466, lng: -66.118},
          {lat: 32.321, lng: -64.757},
          {lat: 25.774, lng: -80.190}
        ];


        var bermudaTriangle = new google.maps.Polygon({
          paths: triangleCoords,
          strokeColor: '#FF0000',
          strokeOpacity: 0.8,
          strokeWeight: 2,
          fillColor: '#FF0000',
          fillOpacity: 0.35
        });
        bermudaTriangle.setMap(map);

Take note of how triangleCoords is structured, it's an array of lat, lng objects. In order to plot the polygon retrieved from your AJAX call, you will need to format it in a similar way with an array of lat, lng objects.

http://jsbin.com/kupeyofemo/edit?html,output

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

Looking for assistance with JQuery and JavaScript?

I oversee a team of employees, each with a 7-day work schedule. To streamline the process, I have developed a PHP form that I would like to use to collect data for verification in JavaScript before submitting it to an SQL database using AJAX. My main cha ...

Is the sliding navigation glitching due to the video background?

Currently, I am in the process of developing a website with a captivating full-page video background. The nav menu gracefully slides out from the left side using jQuery UI when users scroll down to view the site's content. To view the work-in-progres ...

Methods like jQuery blink(), strike(), and bold() offer dynamic ways to manipulate

I'm currently tackling an inquiry. The code I crafted seems to be functioning without any issues: (function () { if($('#target:contains("bold")')) { $('#target span:first').css('font-weight','bold ...

Contrasting the utilization of jQuery versus angular element references within an angular directive

Recently, I have been exploring ways to integrate jQuery into angular. One method I found was by utilizing the link function. $('#slider').slider(); However, I couldn't help but wonder about the disparity between the above code snippet an ...

Updating the values of parent components in Vue.js 3 has been discovered to not function properly with composite API

Here is a Vue component I have created using PrimeVue: <template lang="pug"> Dialog(:visible="dShow" :modal="true" :draggable="false" header="My Dialog" :style="{ width: '50vw' }" ...

Stopping npm private organization from releasing public packages

Is there a method to restrict the publication of public packages within an npm organization? It appears that this scenario would often arise (ensuring that no member of an organization accidentally publishes a package as public when it should be private b ...

What is the solution for addressing the absence of an 'Access-Control-Allow-Origin' header in the requested resource while using axios?

Here is my Vue script: <script> export default { ... methods : { login() { // uri -> http://my-app.test/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="472b28202e2978222a262e2b7a332234330720 ...

Tips on how to display a Vue component on a new page with Vue.js router

My current challenge is getting my App to render on a new page instead of the same page. Despite trying render: h => h(App), it still renders on the same page. This is the Vue file (Risks.vue) where the router will be linked: <router-link to="/risk ...

I am looking to fetch information from a different Firestore collection by looping through data using a forEach method within an onSnapshot function

I'm struggling to grasp the concept of rendering data from Firestore in my project. I've searched extensively but haven't been able to find a solution that fits my requirements. Background Information In my Firestore database, I have collec ...

Keep the music playing by turning the page and using Amplitude.js to continue the song

I have implemented Amplitude.js to play dynamic songs using a server-side php script. My objective is to determine if a song is currently playing, and if so, before navigating away from the page, save the song's index and current position (in percenta ...

Ways to determine the success of $wpdb->query and retrieve the outcome

Currently, I am in the process of developing a WordPress website, I have implemented a form that allows users to make modifications and update the database: Below is the HTML/PHP code snippet: echo '<form class="form-verifdoc" target=&q ...

What methods are available for drawing on an HTML canvas using a mouse?

I am facing two challenges: how can I create rectangles using the mouse on an HTML canvas, and why is my timer not visible? Despite trying various code snippets, nothing seems to be working. Grateful for any help! HTML: <!DOCTYPE html> <html lan ...

Locate the closing anchor tag following the image

I need to locate the closing anchor tag that wraps an image with the class name "cat-image" in order to move a div right after it. However, I am unable to modify the HTML by adding IDs or classes to the anchor or image tags. Below is an example of the HTM ...

My React setup is causing some problems that I need to address

React is not my strong suit, but I need to test a React application. The issue arises when attempting to run the server using gulp nodemon, resulting in numerous errors. It seems that the application is built on an outdated version of React and some libra ...

Transform Django Model Instance from Serialized Back to Object using Ajax

Currently, I'm utilizing Ajax to search for a model instance. Once found, I return that instance and pass it as a variable to a template tag within my template. To achieve this, in my view, I serialize the object before sending it to the Ajax success ...

What is the formula to determine if x is greater than y and also less than z?

I need help determining if a number falls within the range of greater than 0 but less than 8 using JavaScript. Can anyone assist me with this? Here is my attempt at it: if (score > 0 && score < 8) { alert(score); } ...

Transitioning React Hover Navbar Design

I'm currently revamping a click-to-open navbar into a hover bar for a new project. I have successfully implemented the onMouseEnter and onMouseLeave functions, allowing the navbar to open and close on mouse hover. However, I am facing an issue with ad ...

An issue arises when trying to import the modal popup

Hey there! I'm currently trying to implement a modal popup in react-bootstrap, but I keep running into an error that says "Props not defined". I followed the instructions from the react-bootstrap documentation, but I can't seem to figure out what ...

Angular 5 with Typescript encountered a failure in webpack due to the absence of the property "data" on the Response

I am encountering an issue during webpack compilation. It compiles successfully if I remove .data, but then the page crashes with calls from template->component (which in turn calls a service). Here is the error I am facing: ERROR in src/app/components ...

Is there a way to execute an SQL query using ajax?

I recently came across an interesting problem involving passing an SQL query through to an ajax file. let qry = mysqli_query($this->con,"SELECT * FROM products"); To ensure proper containment, I embedded the variable within HTML using the following co ...