Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add static maps component with SSR support #633

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 7 additions & 7 deletions docs/api-reference/components/map.md
Original file line number Diff line number Diff line change
Expand Up @@ -86,10 +86,10 @@ Maps JavaScript API is based on map-views (effectively calls to the
`google.maps.Map` constructor), this can quickly cause a problem.

The `Map` component can be configured to re-use already created maps with
the [`reuseMaps`](#reusemaps-boolean) prop.
When enabled, all `Map` components created with the same [`mapId`](#mapid-string),
[`colorScheme`](#colorscheme-googlemapscolorschemegmp-color-scheme-type) and
[`renderingType`](#renderingtype-googlemapsrenderingtypegmp-rendering-type) will reuse
the [`reuseMaps`](#reusemaps-boolean) prop.
When enabled, all `Map` components created with the same [`mapId`](#mapid-string),
[`colorScheme`](#colorscheme-googlemapscolorscheme) and
[`renderingType`](#renderingtype-googlemapsrenderingtype) will reuse
previously created instances instead of creating new ones.

:::warning
Expand Down Expand Up @@ -162,7 +162,7 @@ of the [Cloud-based maps styling][gmp-map-styling].

The [color-scheme][gmp-color-scheme] to be used by the map. Can be
`'LIGHT'`, `'DARK'`, `'FOLLOW_SYSTEM'` or one of the
`ColorScheme` constants
`ColorScheme` constants
(`import {ColorScheme} from '@vis.gl/react-google-maps';`).

:::note
Expand All @@ -174,7 +174,7 @@ Custom styles that use Map IDs only apply to the light color scheme for roadmap
#### `renderingType`: [google.maps.RenderingType][gmp-rendering-type]

The desired rendering type the renderer should use. Can be `'RASTER'` or
`'VECTOR'` or one of the `RenderingType` constants
`'VECTOR'` or one of the `RenderingType` constants
(`import {RenderingType} from '@vis.gl/react-google-maps';`).

If not set, the cloud configuration for the map ID will determine the
Expand All @@ -196,7 +196,7 @@ style-prop is no longer applied.
#### `reuseMaps`: boolean

Enable map-instance caching for this component. When caching is enabled,
this component will reuse map instances created with the same `mapId`,
this component will reuse map instances created with the same `mapId`,
`colorScheme` and `renderingType`.

See also the section [Map Instance Caching](#map-instance-caching) above.
Expand Down
229 changes: 229 additions & 0 deletions docs/api-reference/components/static-map.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,229 @@
# `<StaticMap>` Component

React component and utility function to create and render [Google Static Maps][gmp-static-map] images. This implementation provides both a React component for rendering and a URL generation utility that supports all Google Static Maps API features. The main purpose of the utility function is to enable 'url-signing' in various
server environments.

The main parameters to control the map are `center`,
`zoom`, `width` and `height`. With a plain map all of these are required for the map to show. There are cases where `center` and `zoom` can be omitted and the viewport can be automatically be determined from other data. This is the case when having markers, paths or other `visible` locations which can form an automatic bounding box for the map view.

Parameters that are always required are `apiKey`, `width` and `height`.

```tsx
import {StaticMap, createStaticMapsUrl} from '@vis.gl/react-google-maps';

const App = () => {
let staticMapsUrl = createStaticMapsUrl({
apiKey: 'YOUR API KEY',
width: 512,
height: 512,
center: {lat: 53.555570296010295, lng: 10.008892744638956},
zoom: 15
});

// Recommended url-signing when in a server environment.
staticMapsUrl = someServerSigningCode(
staticMapsUrl,
process.env.MAPS_SIGNING_SECRET
);

return <StaticMap url={staticMapsUrl} />;
};
```

More on URL signing and digital signatures [here](#digital-signature).

## Props

The `StaticMap` component only has one `url` prop. The recommended way to generate the url is to use the `createStaticMapsUrl` helper function.

### Required

#### `url`: string

An url which can be consumed by the Google Maps Static Api.

### Optional

#### `className`: string

A class name that will be attached to the `img` tag.

## `createStaticMapsUrl` options

:::note

Some explanations and syntax migh differ slighty from the official documentation since the Google documentation focuses on building and URL which has
been abstracted here in the helper function for better developer experience

:::

For more details about API options see the [get started][get-started] guide in the Google documentation.

### Required

#### `apiKey`: string

The Google Maps Api key.

#### `width`: number

Width of the image. Maps smaller than 180 pixels in width will display a reduced-size Google logo. This parameter is affected by the scale parameter; the final output size is the product of the size and scale values.

#### `height`: number

Height of the image. This parameter is affected by the scale parameter; the final output size is the product of the size and scale values.

### Optional

#### `center`: [StaticMapsLocation](#staticmapslocation)

(required if no markers, paths or visible locations are present) Defines the center of the map, equidistant from all edges of the map. This parameter takes a location as either [`google.maps.LatLngLiteral`][gmp-ll] or a string address (e.g. "city hall, new york, ny") identifying a unique location on the face of the earth.

#### `zoom`: number

(required if no markers, paths or visible locations are present) Defines the zoom level of the map, which determines the magnification level of the map. This parameter takes a numerical value corresponding to the zoom level of the region desired.

#### `scale`: number

Affects the number of pixels that are returned. scale=2 returns twice as many pixels as scale=1 while retaining the same coverage area and level of detail (i.e. the contents of the map don't change). This is useful when developing for high-resolution displays. The default value is 1. Accepted values are 1 and 2

#### `format`: 'png' | 'png8' | 'png32' | 'gif' | 'jpg' | 'jpg-baseline'

Defines the format of the resulting image. By default, the Maps Static API creates PNG images. There are several possible formats including GIF, JPEG and PNG types. Which format you use depends on how you intend to present the image. JPEG typically provides greater compression, while GIF and PNG provide greater detail

#### `mapType`: [google.maps.MapTypeId][gmp-map-type-id]

Defines the type of map to construct. There are several possible maptype values, including roadmap, satellite, hybrid, and terrain.

#### `language`: string

Defines the language to use for display of labels on map tiles. Note that this parameter is only supported for some country tiles; if the specific language requested is not supported for the tile set, then the default language for that tileset will be used.

#### `region`: string

Defines the appropriate borders to display, based on geo-political sensitivities. Accepts a region code specified as a two-character ccTLD ('top-level domain') value

#### `mapId`: string

Specifies the identifier for a specific map. The Map ID associates a map with a particular style or feature, and must belong to the same project as the API key used to initialize the map.

#### `markers`: [StaticMapsMarker[]](#staticmapsmarker)

Defines markers that should be visible on the map.

#### `paths`: [StaticMapsPath[]](#staticmapspath)

Defines paths that should be shown on the map.

#### `visible`: [StaticMapsLocation[]](#staticmapslocation)

Specifies one or more locations that should remain visible on the map, though no markers or other indicators will be displayed. Use this parameter to ensure that certain features or map locations are shown on the Maps Static API.

#### `style`: [google.maps.MapTypeStyle[]][gmp-map-type-style]

Defines a custom style to alter the presentation of a specific feature (roads, parks, and other features) of the map. This parameter takes feature and element arguments identifying the features to style, and a set of style operations to apply to the selected features. See [style reference][gmp-style-ref] for more information.

## Digital Signature

:::warning

Please only use URL signing on the server and keep your URL signing secret secure. Do not pass it in any requests, store it on any websites, or post it to any public forum. Anyone obtaining your URL signing secret could spoof requests using your identity.

:::
It is recommended to use a [digital signature][digital-signature] with your Static Maps Api requests.

Digital signatures are generated using a URL signing secret, which is available on the Google Cloud Console. This secret is essentially a private key, only shared between you and Google, and is unique to your project.

The signing process uses an encryption algorithm to combine the URL and your shared secret. The resulting unique signature allows our servers to verify that any site generating requests using your API key is authorized to do so.

- Step 1: [Get your URL signing secret][sign-secret]
- Step 2: Construct an unsigned request with the `createStaticMapUrl` helper.
- Step 3: [Generate the signed request][generate-signed] | [Sample code for URL signing][sample-code]

Google also provides a package [`@googlemaps/url-signature`][url-signature] for URL signing. Another example could look like this. Here in a Next.js environment.

```tsx
import 'server-only';

import {signUrl} from '@googlemaps/url-signature';

export function signStaticMapsUrl(url: string, secret: string): string {
return signUrl(url, secret).toString();
}
```

When the signing process is setup, you can then [limit the unsigned request][limit-unsigned] to prevent abuse of your api key

## Types

### StaticMapsLocation

Reference: [`google.maps.LatLngLiteral`][gmp-ll]

```tsx
type StaticMapsLocation = google.maps.LatLngLiteral | string;
```

### StaticMapsMarker

- For `color`, `size`, `label` see [marker styles][gmp-marker-styles].
- For `icon`, `anchor` and `scaling` see [custom icons][gmp-custom-icons].

```tsx
type StaticMapsMarker = {
location: google.maps.LatLngLiteral | string;
color?: string;
size?: 'tiny' | 'mid' | 'small';
label?: string;
icon?: string;
anchor?: string;
scale?: 1 | 2 | 4;
};
```

### StaticMapsPath

For style options see [Path styles][gmp-path-styles].

`coordinates` can either bei an array of locations/addresses or it can be an [encoded polyline][gmp-encoded-polyline]. Note that the encoded polyline needs an `enc:` prefix.

```tsx
type StaticMapsPath = {
coordinates: Array<google.maps.LatLngLiteral | string> | string;
weight?: number;
color?: string;
fillcolor?: string;
geodesic?: boolean;
};
```

## Examples

Usage examples for many of the API options can be found [here][usage-examples]

## Source

[`./src/components/static-map`][static-map-source]\
[`./src/libraries/create-static-maps-url/index`][create-static-map-url-source]\
[`./src/libraries/create-static-maps-url/types`][create-static-map-url-types]

[gmp-static-map]: https://developers.google.com/maps/documentation/maps-static
[static-map-source]: https://github.com/visgl/react-google-maps/tree/main/src/components/static-map
[create-static-map-url-source]: https://github.com/visgl/react-google-maps/tree/main/src/libraries/create-static-maps-url/index.ts
[create-static-map-url-types]: https://github.com/visgl/react-google-maps/tree/main/src/libraries/create-static-maps-url/types
[gmp-map-type-id]: https://developers.google.com/maps/documentation/javascript/reference/map#MapTypeId
[gmp-ll]: https://developers.google.com/maps/documentation/javascript/reference/coordinates#LatLngLiteral
[gmp-map-type-style]: https://developers.google.com/maps/documentation/javascript/reference/map#MapTypeStyle
[usage-examples]: https://github.com/visgl/react-google-maps/tree/main/examples/static-map
[get-started]: https://developers.google.com/maps/documentation/maps-static/start
[sign-secret]: https://developers.google.com/maps/documentation/maps-static/digital-signature#get-secret
[gmp-encoded-polyline]: https://developers.google.com/maps/documentation/maps-static/start#EncodedPolylines
[gmp-path-styles]: https://developers.google.com/maps/documentation/maps-static/start#PathStyles
[gmp-marker-styles]: https://developers.google.com/maps/documentation/maps-static/start#MarkerStyles
[gmp-custom-icons]: https://developers.google.com/maps/documentation/maps-static/start#CustomIcons
[limit-unsigned]: https://developers.google.com/maps/documentation/maps-static/digital-signature#limit-unsigned-requests
[url-signature]: https://www.npmjs.com/package/@googlemaps/url-signature
[generate-signed]: https://developers.google.com/maps/documentation/maps-static/digital-signature#generate-signed-request
[sample-code]: https://developers.google.com/maps/documentation/maps-static/digital-signature#sample-code-for-url-signing
[digital-signature]: https://developers.google.com/maps/documentation/maps-static/digital-signature
[gmp-style-ref]: https://developers.google.com/maps/documentation/maps-static/style-reference
3 changes: 2 additions & 1 deletion docs/table-of-contents.json
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,8 @@
"api-reference/components/info-window",
"api-reference/components/marker",
"api-reference/components/advanced-marker",
"api-reference/components/pin"
"api-reference/components/pin",
"api-reference/components/static-map"
]
},
{
Expand Down
41 changes: 41 additions & 0 deletions examples/examples.css
Original file line number Diff line number Diff line change
Expand Up @@ -126,3 +126,44 @@ html[data-theme='dark'] .gm-style {
opacity: 0.5;
cursor: default;
}

.static-map-grid,
.static-map-grid * {
box-sizing: border-box;
}

.static-map-grid {
display: grid;
grid-template-rows: 1fr 1fr;
grid-template-columns: 1fr 1fr;
height: 100%;
width: 100%;
gap: 16px;
padding: 16px;
background: darkgray;
}

.static-map-grid .map-container {
display: flex;
position: relative;
}

.static-map-grid .map-container:nth-child(1) {
align-items: flex-end;
justify-content: flex-end;
}

.static-map-grid .map-container:nth-child(2) {
align-items: flex-end;
}
.static-map-grid .map-container:nth-child(3) {
justify-content: flex-end;
}

.static-map-grid .map {
object-fit: contain;
position: absolute;
max-height: 100%;
width: auto;
max-width: 100%;
}
35 changes: 35 additions & 0 deletions examples/static-map/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
# Static Map Example

This is an example to show how to use the `Static Map` component.

## Google Maps Platform API Key

This example does not come with an API key. Running the examples locally requires a valid API key for the Google Maps Platform.
See [the official documentation][get-api-key] on how to create and configure your own key.

The API key has to be provided via an environment variable `GOOGLE_MAPS_API_KEY`. This can be done by creating a
file named `.env` in the example directory with the following content:

```shell title=".env"
GOOGLE_MAPS_API_KEY="<YOUR API KEY HERE>"
```

If you are on the CodeSandbox playground you can also choose to [provide the API key like this](https://codesandbox.io/docs/learn/environment/secrets)

## Development

Go into the example-directory and run

```shell
npm install
```

To start the example with the local library run

```shell
npm run start-local
```

The regular `npm start` task is only used for the standalone versions of the example (CodeSandbox for example)

[get-api-key]: https://developers.google.com/maps/documentation/javascript/get-api-key
31 changes: 31 additions & 0 deletions examples/static-map/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta
name="viewport"
content="width=device-width, initial-scale=1.0, user-scalable=no" />
<title>Static Map Example</title>
<meta name="description" content="Static Map Example" />
<style>
body {
margin: 0;
font-family: sans-serif;
}
#app {
width: 100vw;
height: 100vh;
}
</style>
</head>
<body>
<div id="app"></div>
<script type="module">
import '@vis.gl/react-google-maps/examples.css';
import '@vis.gl/react-google-maps/examples.js';
import {renderToDom} from './src/app';

renderToDom(document.querySelector('#app'));
</script>
</body>
</html>
Loading
Loading