banner



How To Make A Map Drawing Borders On Usa


Geographic Information System (GIS) data can come up in a lot of forms, which can atomic number 82 to confusion in how to represent data. For instance, what would yous telephone call the borders of a certain canton? Would you call it border, coordinates, or outline? Would you utilise longitude and latitude, or some other coordinate arrangement, like altitude from a given user? Mix that with the fact that in that location are multiple map APIs and other applications that will want to bargain with geographical information, and you're likely to end up with a lot of unnecessary format-parsing lawmaking.

Fortunately, to solve this problem, a standard has emerged. Specifically, the standard we volition be talking about today is GeoJSON. GeoJSON is a standard that was initially created in 2008 by the Internet Engineering Task Force, which is a volunteer-staffed, non-turn a profit, open standards operation, with the nearly recent version, RFC 7946, being fabricated in 2022.

In this commodity we'll expect at the GeoJSON format, so use a GeoJSON data ready to draw regional borders on a map with TomTom JavaScript Maps SDK for Web.

Project Setup

Today, we'll exist learning how to leverage GeoJSON to display new boundaries on a map. Specifically, nosotros'll be using the TomTom JavaScript Maps SDK for Web to create a map and describe layers on it to highlight county regions, which are defined by a GeoJSON dataset.

To do this, we'll need:

  • Some GeoJSON coordinates to draw on a map
  • TomTom API, to display the map
  • HTTP-Server, to host the web app

For the GeoJSON, nosotros'll just grab some coordinates from GitHub. This file on GitHub provides the raw GeoJSON information from Paul Bartsch's ca_counties.geojson gist. These coordinates point to the counties of California. There's likewise other data in the dataset to follow the GeoJSON standards, merely all we need are the coordinates of the counties. Download and salve the information every bit script.js. Nosotros will convert the GeoJSON to JavaScript nosotros can apply later.

To get started, you demand the latest version of TomTom JavaScript Maps SDK for Web. Extract the SDK to a folder called sdk in the aforementioned directory as where you'll proceed a simple index.html.

Once you take TomTom SDK, make sure you lot have a valid TomTom API Key, which requires you lot to register an account here.

Finally, y'all need an HTTP-Server to run your spider web app, which tin be obtained via Node and NPM. (As of the time of writing, in that location is a issues with using the most recent version of HTTP-Server to host a spider web app, if you're getting corrupt connexion error, try running the following command to install an older version.)

npm install -m http-server@0.9.0

Project Details

Now that we've got all the requirements gear up, we can start edifice our app!

First, nosotros need to create an index.html page. We demand to import our TomTom SDK. To do that you demand to import maps-web.min.js:

<head> 	<meta http-equiv="10-UA-Compatible" content="IE=Edge" /> 	<meta charset='UTF-8'> 	<title>TomTom Examples</title> 	<meta name='viewport'     content='width=device-width,initial-scale=ane,maximum-scale=1,user-scalable=no'/> 	<link rel='stylesheet' type='text/css' href='sdk/maps.css' /> 	<script src='sdk/maps-web.min.js'></script> 	<script src='script.js'></script> </caput>        

Next, we need to create a DIV for our map. This is all nosotros demand for the body for the purposes of this article.

<body>   <div id='map' grade='employ-all-infinite' style="height: 300px; width: 300px"></div> </body>        

At present that we've made it through the HTML, nosotros can get to the chief meat of this commodity: implementing the map and drawing the layers, via JavaScript. The first thing to practice in JavaScript is to import the GeoJSON data.

In that location are a few ways to do this:

  • you lot can download the file via an HTTP Request
  • you can just manually paste the GeoJSON in a script, which will be represented as a javascript object we would then store in a global variable that other scripts can access it.

 In this tutorial, you'll exist assigning the GeoJSON straight in our JavaScript file. Specifically, in parameter "geoJson", for simplicity'south sake.

Here'south what our map.js looks like:

var geoJson = {   "type": "FeatureCollection",     "features": [     { "type": "Feature", "properties": { "STATEFP": "06", "COUNTYFP": "107", "COUNTYNS": "00277318", "GEOID": "06107", "Proper noun": "Tulare", "NAMELSAD": "Tulare County", "LSAD": "06", "CLASSFP": "H1", "MTFCC": "G4020", "CSAFP": null, "CBSAFP": "47300", "METDIVFP": null, "FUNCSTAT": "A", "ALAND": -2147483648.000000, "AWATER": 37391604.000000, "INTPTLAT": "+36.2288317", "INTPTLON": "-118.7810618" }, "geometry": { "type": "Polygon", "coordinates": [ [ [ -119.475, 36.39 ], [ -119.475, 36.401 ], [ -119.529, 36.401 ], [ -119.527, 36.489 ], [ -119.573, 36.489 ], [ -119.466, 36.575 ], [ -119.305, 36.574 ], [ -119.305, 36.661 ], [ -118.985, 36.657 ], [ -118.982, 36.742 ], [ -118.351, 36.741 ], [ -118.335, 36.705 ], [ -118.366, 36.69 ], [ -118.331, 36.669 ], [ -118.338, 36.655 ], [ -118.321, 36.627 ], [ -118.275, 36.597 ], [ -118.292, 36.562 ], [ -118.239, 36.524 ], [ -118.235, 36.494 ], [ -118.25, 36.482 ], [ -118.216, 36.457 ], [ -118.21, 36.43 ], [ -118.157, 36.433 ], [ -118.139, 36.419 ], [ -118.163, 36.389 ], [ -118.one, 36.346 ], [ -118.128, 36.28 ], [ -118.106, 36.213 ], [ -118.059, 36.17 ], [ -118.074, 36.xiv ], [ -118.067, 36.093 ], [ -118.052, 36.084 ], [ -118.034, 36.009 ], [ -118.004, 35.984 ], [ -118.017, 35.955 ], [ -117.983, 35.927 ], [ -117.981, 35.868 ], [ -118.007, 35.858 ], [ -118.008, 35.789 ], [ -119.538, 35.79 ], [ -119.529, 36.27 ], [ -119.475, 36.269 ], [ -119.475, 36.39 ] ] ] } }, { . . . }  //The rest of the coordinates are omitted        

GeoJSON is provided in the grade of an object, which means we tin set information technology to a variable and be able to admission it anywhere in the JavaScript.

Some other setup step is setting the production information. This can be done with tt.setProductInfo, which keeps rail of the awarding'due south name and version. TomTom'due south new namespace is tt, exist aware that this is a new change that came with TomTom JavaScript Map SDK Version five.

With that out of the way, we can now implement TomTom's map properly in JavaScript. The code is straightforward: tt.map expects an object to configure the map'south options.

Add this code below your trunk tag in index.html.

<script>   tt.setProductInfo('My First App', '1.0');   var map = tt.map({     container: 'map', // Id of the div to insert the map into     cardinal: '<API Primal>',     source: 'vector',     basePath: '/sdk' // Location of the SDK binder   }); </script>        

At present for one last chip of setup, before nosotros can starting time working with the GeoJSON: we demand to create a map load role. This is important, otherwise, the lawmaking we'll write will be executed earlier our map is. We're going to just place information technology inside the script tag, beneath the setting up the map.

<script>   tt.setProductInfo('My First App', '1.0');   var map = tt.map({     container: 'map', // Id of the div to insert the map into     key: '<API Primal>',     source: 'vector',     basePath: '/sdk' // Location of the SDK folder   });   map.on('load',role(){    } </script>        

Alright, it'southward finally time to utilise that GeoJSON!

Nosotros're going to utilize map.addLayer to describe on the map. The addLayer role expects an object, with specific inputs, every bit seen below.

map.on('load',function(){   map.addLayer({     'id': geoJson["features"][0]["backdrop"]["Name"],     'type': 'fill',     'source': {       'type': 'geojson',       'data': {         'type': 'Feature',         'geometry': geoJson["features"][0]["geometry"]       }     },     'layout': {},     'paint': {       'fill-colour': '#088',       'fill-opacity': 0.8     }   }) }        

The most important parts to annotation are the parts that aren't hardcoded. IDs demand to exist unique. You can solve this by using the name of the county you're in!

The Geometry parameter is a bit more complicated, but nevertheless straightforward. It contains some data nearly the coordinates, and so it contains every coordinate needed for the county edge. Our GeoJSON data is formatted perfectly for what the TomTom SDK requires, so we pass it in.

You can now launch the map by running http-server in your binder using Node and using whatever web browser to connect to one of the provided addresses.

Geo1

You lot should see something similar this when y'all admission either of the IP addresses with any browser:

geo2

That'southward all well and good, but that'south only i object! What if we want more than? At that place's dozens in the provided GeoJSON file! Fortunately, there's an piece of cake style to do that. All y'all need to do is create a for-loop to iterate through the value of "features" from our GeoJSON!

Here's the updated script.js:

map.on('load',function(){   for(var i=0;i<geoJson["features"].length;i++){     //Limit it, considering too many breaks the map.     //Most of this code was copied from another provided tutorial.     console.log(i);     map.addLayer({       'id': geoJson["features"][i]["properties"]["NAME"],       'type': 'fill',               'source': {                 'type': 'geojson',                 'data': {                   'blazon': 'Feature',                   'geometry': geoJson["features"][i]["geometry"]                 }               },       'layout': {},       'paint': {         'fill-color': '#088',         'fill-opacity': 0.viii       }     })   } });                                          

If you've run it, you'll probably find one slight trouble. The unabridged map is missing, simply if you lot endeavor to wait around the map, you can see your layers.

eo3

In that location's an upper limit to how many coordinates you tin accept earlier the map doesn't load properly. In this instance, the total number of layers doesn't seem that large. Nonetheless, if you lot await back at the source data, you'll notice that each canton outline tin can contain dozens of coordinates. The more complicated outlines comprise ninety or more coordinates each.

Then, y'all want to exist enlightened of the complexity of your underlying coordinate and layer data to make sure it renders correctly. You as well desire to continue this in mind to brand sure users have a good experience in terms of being able to download your information fix efficiently, fifty-fifty in depression throughput mobile or wifi situations, and your information tin can be processed quickly, even on low-powered devices.

To address this situation for my sample, I just decreased the number of layouts to draw.

map.on('load',office(){   for(var i=0;i<a["features"].length/iv;i++){     //Limit it, because too many breaks the map.     //Most of this code was copied from another provided tutorial.     console.log(i);     map.addLayer({       'id': geoJson["features"][i]["properties"]["NAME"],       'type': 'fill',       'source': {         'type': 'geojson',         'data': {           'type': 'Feature',           'geometry': geoJson["features"][i]["geometry"]         }       },       'layout': {},       'paint': {       'fill up-color': '#088',       'fill-opacity': 0.8       }     })   } });        

A more complete app might prioritize certain nearby counties, or smooth out boundary details not crucial to a zoomed-out view.

Next Steps

In this commodity, we went through implementing TomTom's map, and cartoon layers that were provided by a JSON object that was created in the GeoJSON standard.

You've set up everything needed to create the map, then yous looped through our GeoJSON variable, and finally, you lot created layers to describe on top of a map.

Now that you know how to work with GeoJSON and TomTom'southward Map API, yous can start creating all sorts of apps! Mayhap you want to highlight certain tourist attractions on a map, or mark certain countries that can friction match some trivia location, like "what states are the Appalachian mountains contained in?" The possibilities are endless! Sign upwards for a programmer account and get your complimentary API central to get building today!

If you'd like to learn more about GeoJSON, you can read more about information technology from the RFC document itself, or, if yous're interested in learning more than or participate in GeoJSON'due south development, you can bank check out their piece of work group.

Lastly, check out these related manufactures using GeoJSON:

  • Highlight Important Details with Custom Styling for Routing Sections
  • Displaying Density Heatmap Layers with the TomTom Web SDK
  • Calculation EV Routing to a TomTom Web Map: Building the Spider web Application

Happy mapping!

Source: https://developer.tomtom.com/blog/build-different/using-geojson-geometry-data-draw-borders-tomtom-maps

Posted by: whartonteme1960.blogspot.com

0 Response to "How To Make A Map Drawing Borders On Usa"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel