Skip to content

Instantly share code, notes, and snippets.

@rudimusmaximus
Forked from ConnectExtend/StaticMap.MD
Created November 13, 2018 02:34
Show Gist options
  • Save rudimusmaximus/309a027a4c6f6a846e9d9ab6e0894985 to your computer and use it in GitHub Desktop.
Save rudimusmaximus/309a027a4c6f6a846e9d9ab6e0894985 to your computer and use it in GitHub Desktop.
/**
* Takes a google maps api key and
* a json props object to generate
* a valid URL to a static map image.
* 
* @returns a valid URL to static map image
*/
function getStaticMap(key, props) {
    const markers = (props.markers || []).map(marker => 
		[
      		`&markers=color:${marker.color || 'red'}`,
       		`label:${(marker.label || '').replace('|', '\\|')}`,
        	`${marker.lat},${marker.lng}`
    	].join('|')
	);
    return `https://maps.googleapis.com/maps/api/staticmap?center=${props.lat},${props.lng}&zoom=13&size=${props.width}x${props.height}&maptype=${props.type || 'roadmap'}${markers.join('')}&key=${key}`;
}

Example:

This code:

const data = {
    lat: 40.76,
    lng: -73,
    height: 500,
    width: 500,
    markers: [{
        lat: 40.78,
        lng: -73,
		label: 'X',
		color: 'yellow'
    }]
}
const mapURL = getStaticMap(yourMapsKey, data);

will produce this image:

image

Notes:

  • The label is optional
  • The color is optional (defaults to red)
  • You can have more than one marker, just add it to the passed JSON data
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment