## Overview

Learn how to import [GeoJSON data](https://developers.google.com/maps/documentation/javascript/importing_data.md.txt#data) from either a local or remote
source, and display it on your map. This tutorial uses the map below to
illustrate various techniques to import data into maps.


<iframe src="https://geo-devrel-javascript-samples.web.app/samples/earthquake-markers/app/dist/" allow="fullscreen; "></iframe>

The section below displays the entire code you need to create the map in this
tutorial.

> [!IMPORTANT]
> **Tip:** Check out the [store location solutions](https://developers.google.com/maps/architecture/store-locator.md.txt) to see another example of using GeoJSON data with maps.


### TypeScript

```typescript
let map: google.maps.Map;

function initMap(): void {
  map = new google.maps.Map(document.getElementById("map") as HTMLElement, {
    zoom: 2,
    center: new google.maps.LatLng(2.8, -187.3),
    mapTypeId: "terrain",
  });

  // Create a <script> tag and set the USGS URL as the source.
  const script = document.createElement("script");

  // This example uses a local copy of the GeoJSON stored at
  // http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/2.5_week.geojsonp
  script.src =
    "https://developers.google.com/maps/documentation/javascript/examples/json/earthquake_GeoJSONP.js";
  document.getElementsByTagName("head")[0].appendChild(script);
}

// Loop through the results array and place a marker for each
// set of coordinates.
const eqfeed_callback = function (results: any) {
  for (let i = 0; i < results.features.length; i++) {
    const coords = results.features[i].geometry.coordinates;
    const latLng = new google.maps.LatLng(coords[1], coords[0]);

    new google.maps.Marker({
      position: latLng,
      map: map,
    });
  }
};

declare global {
  interface Window {
    initMap: () => void;
    eqfeed_callback: (results: any) => void;
  }
}
window.initMap = initMap;
window.eqfeed_callback = eqfeed_callback;
```

> [!NOTE]
> **Note:** Read the [guide](https://developers.google.com/maps/documentation/javascript/using-typescript.md.txt) on using TypeScript and Google Maps.

### JavaScript

```javascript
let map;

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

  // Create a <script> tag and set the USGS URL as the source.
  const script = document.createElement("script");

  // This example uses a local copy of the GeoJSON stored at
  // http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/2.5_week.geojsonp
  script.src =
    "https://developers.google.com/maps/documentation/javascript/examples/json/earthquake_GeoJSONP.js";
  document.getElementsByTagName("head")[0].appendChild(script);
}

// Loop through the results array and place a marker for each
// set of coordinates.
const eqfeed_callback = function (results) {
  for (let i = 0; i < results.features.length; i++) {
    const coords = results.features[i].geometry.coordinates;
    const latLng = new google.maps.LatLng(coords[1], coords[0]);

    new google.maps.Marker({
      position: latLng,
      map: map,
    });
  }
};

window.initMap = initMap;
window.eqfeed_callback = eqfeed_callback;
```

> [!NOTE]
> **Note:** The JavaScript is compiled from the TypeScript snippet.

### CSS

```css
/* 
 * Always set the map height explicitly to define the size of the div element
 * that contains the map. 
 */
#map {
  height: 100%;
}

/* 
 * Optional: Makes the sample page fill the window. 
 */
html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
}
```

### HTML

```html
<html>
  <head>
    <title>Earthquake Markers</title>

    <link rel="stylesheet" type="text/css" href="./style.css" />
    <script type="module" src="./index.js"></script>
  </head>
  <body>
    <div id="map"></div>

    <!-- 
      The `defer` attribute causes the script to execute after the full HTML
      document has been parsed. For non-blocking uses, avoiding race conditions,
      and consistent behavior across browsers, consider loading using Promises. See
      https://developers.google.com/maps/documentation/javascript/load-maps-js-api
      for more information.
      -->
    <script
      src="https://maps.googleapis.com/maps/api/js?key=AIzaSyB41DRUbKWJHPxaFjMAwdrzWzbVKartNGg&callback=initMap&v=weekly"
      defer
    ></script>
  </body>
</html>
```

<br />

## Loading data

This section shows you how to load data from either the same domain as your
Maps JavaScript API application, or from a different one.

### Loading data from the same domain

The [Google Maps Data Layer](https://developers.google.com/maps/documentation/javascript/datalayer.md.txt)
provides a container for arbitrary geospatial data
(including GeoJSON). If your data is in a file hosted on the same domain
as your Maps JavaScript API application, you can load it
using the `map.data.loadGeoJson()` method. The file must be on the same domain,
but you can host it in a different
subdomain. For example, you can make a request to **files.example.com** from
**www.example.com**.

```javascript
map.data.loadGeoJson('data.json');
```

### Loading data across domains

You can also request data from a domain other than your own, if the domain's
configuration allows such a request. The standard for this permission is
called
[Cross-origin resource sharing](http://en.wikipedia.org/wiki/Cross-origin_resource_sharing)
(CORS). If a domain has allowed cross-domain requests, its response header
should include the following declaration:

```javascript
Access-Control-Allow-Origin: *
```

Use the
[Chrome Developer Tools (DevTools)](https://developer.chrome.com/devtools#console)
to find out if a domain has enabled CORS.

![](https://developers.google.com/static/maps/documentation/javascript/images/allow_origin.png)

Loading data from such a domain is the same as
loading JSON from the same domain:

```javascript
map.data.loadGeoJson('http://www.CORS-ENABLED-SITE.com/data.json');
```

## Requesting JSONP

The target domain must support requests for [JSONP](https://developers.google.com/maps/documentation/javascript/importing_data.md.txt#JSONP) in order to use
this technique.

> [!WARNING]
> **Requesting JSONP from domains outside of your control is very
> risky.**
>
> Since your browser loads any code that returns as a script, you should only
> request JSONP from a domain that you trust. In general, JSONP is replaced by
> [CORS](https://developers.google.com/maps/documentation/javascript/importing_data.md.txt#loading_data_across_domains); the latter is
> much safer and should be your preferred choice if both are available.

To request JSONP, use `createElement()` to add a `script` tag
to the head of your document.

```javascript
var script = document.createElement('script');
script.src = 'http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/2.5_week.geojsonp';
document.getElementsByTagName('head')[0].appendChild(script);
```

When the script runs, the target domain passes the data as an argument
to *another* script, usually named `callback()`. The target domain defines the
callback script name, which is the first name on the page when you load the
target URL in a browser.

For example, load
<http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/2.5_week.geojsonp>
in your browser window to reveal the callback name as `eqfeed_callback`.

![](https://developers.google.com/static/maps/documentation/javascript/images/callback_name.png)

You must define the callback script in your code:

```javascript
function eqfeed_callback(response) {
  map.data.addGeoJson(response);
}
```

Use the `addGeoJson()` method to place the parsed GeoJSON data on the map.

## Import GeoJSON geometry objects

The `map.data.addGeoJson()` method requires a parsed GeoJSON `Feature` or
`FeatureCollection` object. It does not accept standalone GeoJSON geometry
objects (`Point`, `MultiPoint`, `LineString`, `MultiLineString`, `Polygon`,
`MultiPolygon`, or `GeometryCollection`) directly.

If your data source or API response returns a standalone GeoJSON geometry
object without a top-level `"type": "Feature"` wrapper, you must wrap it in a
`Feature` object before calling `map.data.addGeoJson()`.

For example, if the geometry (such as a `Polygon`) is a parsed JavaScript
object, wrap it in a `Feature` object:

```javascript
const polygonGeometry = {
  type: "Polygon",
  coordinates: [
    [
      [-78.45, 35.82],
      [-78.41, 35.73],
      [-78.28, 35.66],
      [-78.45, 35.82],
    ],
  ],
};

const geoJsonFeature = {
  type: "Feature",
  geometry: polygonGeometry,
};

map.data.addGeoJson(geoJsonFeature);
```

If the geometry is returned as a JSON-formatted string (for example, the
`polygon` field returned by a weather alert or boundary response), you can also
prepend a header and append a footer to form a valid GeoJSON `Feature` before
parsing it with `JSON.parse()`:

```javascript
const geojson_header = "{\"type\":\"Feature\", \"geometry\": ";
const geojson_footer = "}";

map.data.addGeoJson(
    JSON.parse(geojson_header + polygon + geojson_footer));
```

For more information on working with geometries and polygons in the Data layer,
see the [Data Layer developer's guide](https://developers.google.com/maps/documentation/javascript/datalayer.md.txt).

## Styling the data

You can change the appearance of your data by adding GeoJSON data to a Map
object.
Read the developer's guide for more information on
[styling your data](https://developers.google.com/maps/documentation/javascript/datalayer.md.txt#style_geojson_data).

## Learn more

- GeoJSON is a widely used open format for encoding geographic data, based on JSON (JavaScript Object Notation). JavaScript tools and methods designed for JSON data also work with GeoJSON. Read the [developer's guide](https://developers.google.com/maps/documentation/javascript/datalayer.md.txt#load_geojson) for more information.
- JSONP stands for *padded* JSON. It is a communication method used in JavaScript programs that run in web browsers, to request data from a server in a different domain.