Skip to content

Instantly share code, notes, and snippets.

@ConnectExtend
Last active September 14, 2019 00:43
Show Gist options
  • Save ConnectExtend/c9c65e1f9b84886ff7f5a07c96320c5a to your computer and use it in GitHub Desktop.
Save ConnectExtend/c9c65e1f9b84886ff7f5a07c96320c5a 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