Skip to content

Instantly share code, notes, and snippets.

@franklinharvey
Last active January 7, 2021 18:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save franklinharvey/434a4ef2f781be931e7efa92003a348c to your computer and use it in GitHub Desktop.
Save franklinharvey/434a4ef2f781be931e7efa92003a348c to your computer and use it in GitHub Desktop.
Google Maps API v3.0 and react-google-maps snippets

Kind of a barebones approach to draggable markers, saving the new position in state By Franklin Harvey

interface MarkerProps {
    position: google.maps.LatLng
    onDragMarker(e: google.maps.MouseEvent): void
}

DraggableMarker = (props: MarkerProps) => (
    <Marker
        position={props.position}
        draggable
        onDragEnd={props.onDragMarker}
    /> 
)

... in some component class ...

render() {
    return (
        <DraggableMarker 
            position={this.state.markerPosition}
            onDragMarker={this.onDragMarker}
        />
    )
}

onDragMarker = (e: google.maps.MouseEvent) => {
    this.setState({
        markerPosition: e.latLng
    })
}
/*
*
* Get an angle between 0 and 360 degrees from an input of two points
* Can be used to measure angles on a map using markers
* Example: https://imgur.com/a/sU4NwCX
*
* By Franklin Harvey
*
*/
const getAngle = (points: [google.maps.LatLng, google.maps.LatLng]): number => {
let angle: number = google.maps.geometry.spherical.computeHeading(points[0], points[1])
// google maps always spits out (-180, 180]
if (angle < 0) {
angle += 360
}
return angle
}
/*
*
* Get some position which is x distance and n heading from origin position
* Can be used to rotate one marker around another
* Example: https://imgur.com/a/sU4NwCX
*
* By Franklin Harvey
*
*/
const onAngleChange = (points: [google.maps.LatLng, google.maps.LatLng], angle: number): [google.maps.LatLng, google.maps.LatLng] => {
const origin = points[0]
// get distance, so pivoting is consistent distance
const distance: number = google.maps.geometry.spherical.computeDistanceBetween(origin, points[1])
// get new google LatLng
const newPosition: google.maps.LatLng = google.maps.geometry.spherical.computeOffset(origin, distance, angle)
return [origin, newPosition]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment