JavaScript is failing to render various polygons from JSON data

I am attempting to include multiple polygons for London boroughs, but I am encountering an issue where I can't display more than one polygon at a time. Additionally, when I change the order of the boroughs, the polygon disappears. Here is the HTML function code that I'm using:

<script>
function initialize() {
    var map = new google.maps.Map(document.getElementById('map_canvas'), {
        center: new google.maps.LatLng(51.50722, -0.12750), 
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        zoom: 11 
    });
    var points = new google.maps.MVCArray();
    for (var y in borough) {
        var area = borough[y];
        var location = new google.maps.LatLng(area.lat,area.lng);
        points.push(location );
        }
    var polygonOptions = {path:points,map:map, fillColor:"#d3d3d3"};
    var polygon1 = new google.maps.Polygon(polygonOptions);
    var polygon2 = new google.maps.Polygon(polygonOptions);
    polygon.setMap(map); 

    var polyline = new google.maps.Polyline({path:points,map:map});
    }
    google.maps.event.addDomListener(window, 'load', initialize);
</script>
var borough = [{"name":"City of London","PointID":1,"PolygonID":294,"SubPolygonID":1,"lat":51.52028098,"lng":-0.085197314,"AvgPropertyVal":532562},
{"name":"City of London","PointID":2,"PolygonID":294,"SubPolygonID":1,"lat":51.51976087,"lng":-0.08330491,"AvgPropertyVal":532562},
{"name":"City of London","PointID":3,"PolygonID":294,"SubPolygonID":1,"lat":51.52070385,"lng":-0.081741648,"AvgPropertyVal":532562},
...
...[data continues]
...
{"name":"City of London","PointID":55,"PolygonID":294,"SubPolygonID":1,"lat":51.51875522,"lng":-0.08620691,"AvgPropertyVal":532562,},
{"name":"City of London","PointID":56,"PolygonID":294,"SubPolygonID":1,"lat":51.52028098,"lng":-0.085197314,"AvgPropertyVal":532562},

];

Answer №1

To dynamically generate the polygons, follow this code snippet:

function initialize() {
    var map = new google.maps.Map(document.getElementById('map_canvas'), {
        center: new google.maps.LatLng(51.50722, -0.12750),
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        zoom: 11
    });
    var points = new google.maps.MVCArray();
    var areas = [];
    for (var x in borough) {
        var area = borough[x];
        if (!areas[area.name]) areas[area.name] = [];
        areas[area.name].push(new google.maps.LatLng(area.lat, area.lng));
    }
    for (name in areas) {
        var polygonOptions = {
            path: areas[name],
            map: map,
            fillColor: "#d3d3d3"
        };
        var polygon = new google.maps.Polygon(polygonOptions);
        polygon.setMap(map);

        var polyline = new google.maps.Polyline({
            path: areas[name],
            map: map
        });
    }
}
google.maps.event.addDomListener(window, 'load', initialize);

Check out the working demo on jsfiddle

Below is a sample HTML and CSS code snippet:

Sample JavaScript code snippet goes here...
html, body, #map_canvas {
    height: 100%;
    width: 100%;
    margin: 0px;
    padding: 0px;
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map_canvas" style="width:750px; height:450px; border: 2px solid #3872ac;"></div>

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

Transitioning from jQuery to Prototype

After switching from a jQuery background to Prototype, I am curious if there is a chart available that shows the equivalent prototype methods for specific jQuery methods? To be more specific, I am searching for the equivalent of $('#my-id').prep ...

Dynamic Parameter (?) in NodeJS Sqlite WHERE IN Query Statement

In my Node application, I encountered an issue with using dynamic parameters in my SQLITE statements. Specifically, when trying to implement a WHERE IN query, no results were returned. This suggests that the dynamic parameter is being misinterpreted. Below ...

Exploring tree traversal in object mapping using Jackson JSON

I am currently working with JSON data that I need to map to an object in Java. { "response": { "original": { "status": { "code": "SUCCESS" }, "organisationNode": [ { ...

Activate a switch in a single table after its information has been transferred to a different table

I have a dilemma involving two tables - one displaying a list of items and the other serving as an empty favorites table. Users can select items from the first table and click 'Add' to move them to the favorites table. Once added, the 'Add& ...

What methods work best for retrieving non-API data in Next.js when deploying on Vercel?

Before rendering my application, I am working on fetching my data. Luckily, Next.js offers a method called getStaticProps() for this purpose. Currently, I am utilizing the fs module to retrieve data from a json file in my local directory. export async fun ...

Utilizing jQuery functions within an iframe environment

I couldn't find a solution to this problem even after thorough research on Stack Overflow. I am coding in JavaScript and trying to create an iframe where I can load jQuery into it. My goal is to be able to execute methods like $ajax within the context ...

Executing Javascript on Selenium RC with PHP is a crucial skill to have in your toolkit

Is there a way to execute Javascript from Selenium RC? I have been trying different methods with no success so far. I attempted the following approach: I created a custom function in user-extensions.js: function sayhello() { document.write('hel ...

eliminating reliance on promises

I understand the importance of promises, however I am faced with a challenge as I have multiple old functions that currently operate synchronously: function getSomething() { return someExternalLibrary.functionReturnsAValue() } console.log(getSomething( ...

I need to verify that the input type for time is valid, starting from today's date and extending beyond the current

<input type="date" onChange={(e)=>setDate(e.target.value)}/> <input type="time" onChange={(e)=>setTime(e.target.value)} /> If the selected date is after today and the time is after the current time, display a valida ...

There seems to be a complete absence of rendering in this particular vue

Upon initializing a fresh Vue project using Vue CLI 3 and removing all default views and components, I proceeded to add two new views. To my surprise, these views did not render when changing the URL; instead, I was met with a blank page and no error messa ...

A guide on incorporating JSX file rendering in Flask

I am currently working on integrating React Contact form with MYSQL Workbench using Flask. I have set up the database initialization and model using SQLAlchemy, but I am encountering an issue with the render_template function. Is it possible to render th ...

What is the best way to develop a card stack swiper similar to Tinder using React?

After experimenting with various packages, I found that none were satisfactory for creating a customizable card swiper. As a result, I am now considering developing my own solution. What would be the best approach for adding animations, enabling draggable ...

Convert an array of strings in C# into a JSON array using serialization

In my _Layout.cshtml file, I have the following code. The purpose is to populate some security items in my JavaScript code. LoggedIn and username work fine, but there seems to be an issue with how the roles are being displayed in the JavaScript. The Roles ...

Creating and accessing a temporary binary file using Node Js

Challenge I have been working on integrating the Google Text To Speech (TTS) service to save a generated binary audio file to Google Cloud Storage (GCS). Considering that saving a local binary file in Firebase's Cloud Functions environment may not b ...

Locate the position of an element within an array using AngularJS

Consider the following array: $scope.records = [ { "Name" : "Alfreds Futterkiste", "Country" : "Germany" }, { "Name" : "Berglunds snabbköp", "Country" : "Sweden" }, { "Name" : "Centro comercial Moctezum ...

WebAssembly (Wasm) integration of DEC64 implementation

Could a WebAssembly (Wasm) implementation of DEC64[1] be feasible? Please note: I do not specialize in systems development, but I am open to attempting the implementation if there are no major obstacles. The issue at hand: While working with financial so ...

Streaming RTMP video through a WebView

Currently, I am working on implementing rtmp streaming using WebView. To achieve this, I referred to the code provided on Stack Overflow under this link The easiest way to play an audio RTMP stream in Android, which was shared by a user named Club. After a ...

Utilizing a single controller in multiple locations within AngularJS

I am currently working on developing an Ionic application which includes screens with lists containing checkboxes and the option to select all items. My experience with AngularJS and Ionic is fairly limited. The "Select All" functionality works as intende ...

The 405 method not allowed error pops up when trying to use Ajax Delete immediately after

I encountered an issue while trying to remove a vehicle from the table. Everything was working fine on my localhost (Visual Studio), but when I published the project, I started getting a 405 Method Not Allowed error. http://localhost:41904/api/vehicles/42 ...

Workers in Async.js queue failing to complete tasks

Creating a job queue to execute copy operations using robocopy is achieved with the following code snippet: interface copyProcessReturn { jobId: number, code: number, description: string, params: string[], source: string, target: s ...