Trouble viewing Geojson map on website

I'm having trouble generating a map. I am currently working with one of the geojson files provided by The New York Times ("census_tracts_2010.geojson") from this link ( https://github.com/dwillis/nyc-maps ).

If someone could take a look at my code below, I would greatly appreciate it. I can't figure out why the map is not appearing on my end, even though there are no error messages showing up. Any insight into what might be going wrong would be helpful, especially in the last two lines of code.

STEP 1 - CONVERTING GEOJSON TO TOPOJSON I ran the following command in terminal:

geo2topo census_tracts_2010.geojson > nyc2.json

STEP 2 I created an index.html file that was inspired by )

<!DOCTYPE html>
<meta charset="utf-8">
<style>
</style>
<body>
<script src="//d3js.org/d3.v3.min.js" charset="utf-8"></script>
<script src="//d3js.org/topojson.v1.min.js"></script>

<script>

var width = 960,
    height = 1160;

var svg = d3.select("body").append("svg")
    .attr("width", width)
    .attr("height", height);

d3.json("nyc2.json", function(error, uk) {
  if (error) return console.error(error);
  console.log(uk.objects)
  console.log(uk.objects.census_tracts_2010)
  svg.append("path")
      .datum(topojson.feature(uk, uk.objects.census_tracts_2010))
      .attr("d", d3.geo.path().projection(d3.geo.albersUsa()));


});

</script>

Current output: Blank white webpage

Revised code:

<!DOCTYPE html>
<meta charset="utf-8">
<style>
</style>
<body>
<script src="//d3js.org/d3.v3.min.js" charset="utf-8"></script>
<script src="//d3js.org/topojson.v1.min.js"></script>

<script>

var width = 500,
    height = 500;

var svg = d3.select("body").append("svg")
    .attr("width", width)
    .attr("height", height);

d3.json("census_tracts_2010.geojson", function(error, uk) {
  if (error) return console.error(error);

  var subunits = topojson.feature(uk, uk.objects.nyct2010);

  var projection = d3.geo.albers()
   .center([0,40.7])
   .rotate([-74,0])
   .translate([width/2,height/2])
   .scale(65000);

   var path = d3.geo.path()
    .projection(projection);

    svg.append("path")
        .datum(subunits)
        .attr("d", path);
});

</script>

Answer №1

Data Source

Initially, the provided file is already in topojson format. A comparison with a standard geojson file from the same repository can illustrate the differences between the two formats.

A prominent variance is that geojson utilizes familiar coordinates, while topojson employs arcs and seemingly arbitrary coordinates. Topojson files also conclude with scale and translate values.

The Issue at Hand

If your map isn't visible, it could be due to attempting to convert a file that is already in topojson format, or more likely, because you haven't focused your map on the specific area of interest. This seems to align with your previous inquiry as well.

You are currently using a geo.albersUsa projection, which inherently encompasses the entire continental US including Alaska and Hawaii by default.

By exclusively utilizing the referenced topojson file (census_tracts_2010), I obtained:

https://i.sstatic.net/0O5U4.png

Your map does display correctly based on the code, but the entire area of interest may appear too small due to improper focusing.

AlbersUSA vs Albers

To address this, you may need to adjust your map projection parameters. Maintaining the AlbersUSA projection may limit your ability to center or rotate the map; consider switching to a plain Albers projection instead. AlbersUSA is tailored for national-scale maps without options for centering or rotating methods.

Defining Map Parameters

An Albers projection requires specifying the center latitude and longitude of your focused region. For instance, around 40.7N and 74W based on general estimations from Google Earth, adjusted for better results.

While Albers usually involves setting standard parallels, D3's default parallels suffice for US projections. Specific parallels can enhance your map accuracy, though they're omitted herein.

In D3, an Albers projection setup includes:

var projection = d3.geo.albers()
   .center([0,y])
   .rotate([-x,0])
   .parallels([a,b]) // irrelevant here
   .translate([width/2,height/2])
   .scale(k);

By applying the center coordinates and refining the scale, a proper mapping outcome can be achieved:

https://i.sstatic.net/bN6pT.png

Utilizing the following configuration:

var projection = d3.geo.albers()
   .center([0,40.7])
   .rotate([74,0])
   .translate([width/2,height/2])
   .scale(65000);

Note: SVG dimensions were adjusted to match the shape of the area of interest (500 x 500) rather than the reference map dimensions used in the UK example.

For further elaboration on Albers projection parameters, see this informative response.

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

Having trouble with transferring JSON data as a string from POSTMAN to a node server

My JSON data structure is as follows: const json = { "name": "Peter", "age": 21 } After calling JSON.stringify(json), the result is: '{"name":"Peter","age":21}' I am currently us ...

Transform JSON into a format that is compatible with Prometheus for easy reading

I'm currently facing an issue with converting my API response from JSON format to Prometheus format. I've tried using jq and other methods but haven't been successful in capturing the metrics on the Prometheus UI. { "version": &q ...

Vue3 - Implementing a seamless communication channel between two child components

Vue 3 has brought about changes in my component structure, as shown below: https://i.sstatic.net/bgtPB.png In this setup, ChildA can communicate with ChildB and requires ChildB to update its state accordingly. In Vue 2, I could send an event from ChildA: ...

How to send parameters through the Google Maps API URL using Vue.js

When using $router.push(), I receive two parameters: {{ this.$route.params.lat }} and {{ this.$route.params.lng }}, which are latitude and longitude coordinates. To access a Google Maps URL, I need to include both of these parameters: https://maps.googlea ...

The length property of a jQuery array may not always match the actual length of the array

Recently delving into jquery, I encountered the issue described in the title. Below is an excerpt from my controller code: [HttpPost] public JsonResult getProjectList() { List<Project> projectList = new List<Project>(); ...

What is the best way to display a specific object prop on a page after triggering the onChange() method from a selected

Looking to simplify some code that's become a bit overwhelming. My pizza order consists of arrays for size and price. I'm trying to update the price when a user selects a size, but I've been stuck on an issue with mapping pizzas from the ca ...

Looking for a specific value prior to the '.' character in BASH

I need some help with outputting values in JSON format. I noticed that if a value starts with a '.', it causes issues because the API doesn't like integers inside quotation marks. Can someone suggest the best approach to check if a value has ...

Is there a way to adjust the opacity of the JSON model within a Three.js environment?

This masterpiece serves as my JSON model. painting I have grasped that I can adjust the transparency by modifying "transparent":true, and "opacity": 0.5 in the JSON file. Yet, I am keen on altering the opacity of the model post JSON model loading in the ...

Utilizing Highcharts/Highstock for handling large volumes of data efficiently

Dealing with a growing amount of data daily (currently over 200k MySQL rows in one week), the chart loading speed has become quite slow. It seems like using async loading is the solution (http://www.highcharts.com/stock/demo/lazy-loading). I attempted to i ...

What is the best way to locate an element with the class name being an email address using jQuery?

Is it possible to locate an element with an email address as the class name, considering that the email address varies? $(document).ready(function(){ //not working getting error var email="<a href="/cdn-cgi/l/email-protection" class="__cf_email__ ...

Incorporate a progress bar into the Material-UI table design

I have the following example of a Material-UI table: import React from "react"; import clsx from "clsx"; import { createStyles, lighten, makeStyles, Theme } from "@material-ui/core/styles"; import Table from "@mat ...

The code is throwing an error stating that it is unable to determine the length of an

My code is throwing the following error: cannot read property length of undefined in arr[i].length function filterArray(arr, elem) { let newArray = []; for (let i = 0; i < arr.length; i++) { for (let j = 0; j < arr[i].length; j++) { ...

Check if the page has been loaded using Jquery

Can anyone share a helpful strategy for initiating a function in JavaScript that only begins once the entire page has finished loading? ...

The dynamic drop-down menu is giving incorrect values when the onchange function is called

Trying to implement Google Analytics tracking on my dynamic dropdown menu in WordPress has been a bit tricky. I want to be able to track when users click on any of the options and display the name of the selected value, not just the ID. However, I've ...

SOLVING the issue of page flicker in SVELTE

Within the application below, I am experiencing a peculiar page flicker effect that is often associated with AJAX requests. However, in this scenario, the cause is not AJAX-related but rather a conditional statement that triggers the rendering of different ...

The CSS and Bundle script path may need adjustment following the creation of the index.html file by WebPack

There seems to be an issue with webpack trying to add 'client' to the href of script tags for my CSS and bundle files. This is causing a problem as it's incorrect and I'm unsure how to remove it. Prior to switching to webpack, here&apo ...

Using Node.js Express to pass data from both the URL and session into a JavaScript file being served

I've been working on a web-socket application where the client connects to a game instance and the server then links the client to the corresponding Socket.io room for transmitting information. For example, connecting to '/game/abc' would lo ...

Exploring the Depths of Angular Reactive Forms with Recursion

Dealing with recursion and form groups app-root.component.html <div [formGroup]="form"> some content <app-root></app-root> </div> Is it possible to implement the same form group and form controls in my recursive structure? For ex ...

Nodes are being created as JSON attributes

I have a JSON file that I need to convert to XML format. Below is the code snippet I am using to accomplish this task, utilizing the Newtonsoft Json Converter XmlDocument doc = (XmlDocument)JsonConvert.DeserializeXmlNode(json); The input file looks lik ...

Tips for preserving the state of the Material-UI AutoComplete during component re-renders?

Currently, I am utilizing the Material-UI v4 AutoComplete component along with the renderOption prop in order to display a checkbox item option. The issue arises when the onChange event occurs and updates a hook in the parent component causing a re-rende ...