react-map-gl#NavigationControl JavaScript Examples
The following examples show how to use
react-map-gl#NavigationControl.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Map.js From circles-website with GNU Affero General Public License v3.0 | 6 votes |
render() {
const { viewport } = this.state;
return (
<div style={{ height: 600 }}>
<MapGL
{...viewport}
width="100%"
height="100%"
mapStyle="mapbox://styles/mapbox/dark-v9"
onViewportChange={this._updateViewport}
mapboxApiAccessToken={TOKEN}
>
<Pins data={CITIES} onClick={this._onClickMarker} />
{this._renderPopup()}
<div style={geolocateStyle}>
<GeolocateControl />
</div>
<div style={fullscreenControlStyle}>
<FullscreenControl />
</div>
<div style={navStyle}>
<NavigationControl />
</div>
<div style={scaleControlStyle}>
<ScaleControl />
</div>
{/* <ControlPanel containerComponent={this.props.containerComponent} /> */}
</MapGL>
</div>
);
}
Example #2
Source File: TemporalMap.js From sampo-ui with MIT License | 5 votes |
render () {
const { viewport, memory, dates } = this.state
const { classes, animateMap, portalConfig } = this.props
const { mapboxAccessToken, mapboxStyle } = portalConfig.mapboxConfig
return (
<div id='temporal-map-root' ref={this.mapElementRef} className={classes.root}>
<ReactMapGL
{...viewport}
width='100%'
height='100%'
reuseMaps
mapStyle={`mapbox://styles/mapbox/${mapboxStyle}`}
preventStyleDiffing
mapboxApiAccessToken={mapboxAccessToken}
onViewportChange={this.handleOnViewportChange}
>
<div className={classes.navigationContainer}>
<NavigationControl />
<FullscreenControl
className={classes.fullscreenButton}
container={document.querySelector('temporal-map-root')}
/>
</div>
<DeckGL
layers={this._renderLayers()}
viewState={viewport}
/>
<TemporalMapTimeSlider
mapElementRef={this.mapElementRef}
memory={memory}
dates={dates}
animateMap={animateMap}
initialValue={this.props.animationValue[0]}
sliderDuration={portalConfig.temporalMapConfig.sliderDuration}
/>
{this._renderTooltip()}
</ReactMapGL>
</div>
)
}
Example #3
Source File: Map.js From webpage with MIT License | 5 votes |
function LocationMap(){
const { venue } = settingsData()
const width = useWindowWidth()-15
const [viewport, setViewport] = useState({
latitude: venue.lat,
longitude: venue.lng,
zoom: 7,
width: '100vw',
height: "600px",
})
if(width != viewport.width){
setViewport({
...viewport,
width: width
})
}
return(
<Map
mapStyle="mapbox://styles/mapbox/streets-v9"
mapboxAccessToken={process.env.MAPS_KEY}
onViewportChange={setViewport}
scrollZoom={false}
initialViewState={viewport}
style={{ width:viewport.width, height:viewport.height }}
>
<Marker latitude={venue.lat} longitude={venue.lng} offsetLeft={-20} offsetTop={-10}>
<LocationIcon fontSize="large" />
</Marker>
<div style={styles.navigationControl}>
<NavigationControl />
</div>
<div className="card-of-venue-cls" style={styles.cardOfVenue}>
<CardOfVenue />
</div>
</Map>
)
}
Example #4
Source File: modal.js From shopping-cart-fe with MIT License | 4 votes |
Modal = ({ show, user, place }) => {
const [local, setLocal] = useState(
JSON.parse(localStorage.getItem("response")) || [50, 50]
)
const [selected, setSelected] = useState(false)
const [viewPort, setViewPort] = useState({
latitude: local.lat,
longitude: local.lng,
width: "30vw",
height: "20vh",
zoom: 12,
})
return (
<div
className="modal-wrapper"
style={{
transform: show ? "translateY(0vh)" : "translateY(-100vh)",
opacity: show ? "1" : "0",
}}
>
{place && (
<div className="modal-header">
<h3>
{user.businessName} | {user.address}, {user.city}{" "}
{user.state}, {user.zipcode}
</h3>
<p>Phone Number: {user.phone}</p>
<p>Working Hours: {user.hours}</p>
<p>Curb Hours: {user.curbHours}</p>
<a
href={`https://www.google.com/maps/search/?api=1&query=${place.geometry.location.lat},${place.geometry.location.lng}&query_place_id=${place.place_id}`}
>
Get Direction
</a>
</div>
)}
<div className="modal-body">
{place ? (
<div className="mapContainer">
<ReactMapGL
{...viewPort}
mapboxApiAccessToken={mapboxApiToken}
// mapStyle = "mapbox://styles/ariuka11/ckcgwlimk0ldc1iob71hc4s2h"
mapStyle="mapbox://styles/ariuka11/ckcgwq30x0a8k1ip68ajqruoo"
// mapStyle = "mapbox://styles/ariuka11/ckcb5g7ne3rbq1inu8kc7dqye"
onViewportChange={(viewPort) => {
setViewPort(viewPort)
}}
>
<Marker
latitude={place.geometry.location.lat}
longitude={place.geometry.location.lng}
offsetLeft={-20}
className="marker"
>
<button
onClick={(e) => {
e.preventDefault()
setSelected(true)
}}
>
<img src={location} alt="marker" />
</button>
</Marker>
{selected && (
<Popup
latitude={place.geometry.location.lat}
longitude={place.geometry.location.lng}
onClose={() => {
setSelected(false)
}}
>
<h3>{user.address},</h3>
<p style={{ fontSize: "1.5rem" }}>
{user.city} {user.state}, {user.zipcode}
</p>
</Popup>
)}
<div style={{ position: "absolute", right: 0 }}>
<NavigationControl />
</div>
<div style={{ position: "absolute", left: 0 }}>
<GeolocateControl
positionOptions={{ enableHighAccuracy: true }}
trackUserLocation={true}
/>
</div>
</ReactMapGL>
</div>
) : (
<div>No Map</div>
)}
</div>
</div>
)
}
Example #5
Source File: Deck.js From sampo-ui with MIT License | 4 votes |
render () {
const { classes, layerType, fetching, results, showTooltips, portalConfig } = this.props
const { mapboxAccessToken, mapboxStyle } = portalConfig.mapboxConfig
const { hoverInfo } = this.state
const showTooltip = showTooltips && hoverInfo && hoverInfo.object
const hasData = !fetching && results && results.length > 0 &&
(
(results[0].lat && results[0].long) ||
(results[0].from && results[0].to) ||
results[0].polygon
)
// console.log(hasData)
/* It's OK to create a new Layer instance on every render
https://github.com/uber/deck.gl/blob/master/docs/developer-guide/using-layers.md#should-i-be-creating-new-layers-on-every-render
*/
let layer = null
if (hasData) {
switch (layerType) {
case 'arcLayer':
layer = this.createArcLayer(results)
break
case 'heatmapLayer':
layer = this.createHeatmapLayer(results)
break
case 'hexagonLayer':
layer = this.createHexagonLayer(results)
break
case 'polygonLayer':
layer = this.createPolygonLayer(results)
break
default:
layer = this.createHeatmapLayer(results)
break
}
}
return (
<div className={classes.root}>
<ReactMapGL
{...this.state.viewport}
width='100%'
height='100%'
reuseMaps
mapStyle={`mapbox://styles/mapbox/${mapboxStyle}`}
preventStyleDiffing
mapboxApiAccessToken={mapboxAccessToken}
onViewportChange={this.handleOnViewportChange}
>
<div className={classes.navigationContainer}>
<NavigationControl />
<FullscreenControl
className={classes.fullscreenButton}
container={document.querySelector('mapboxgl-map')}
/>
</div>
{layerType === 'arcLayer' &&
<HTMLOverlay redraw={() =>
<DeckArcLayerLegend
title={this.props.legendTitle}
fromText={this.props.legendFromText}
toText={this.props.legendToText}
/>}
/>}
<DeckGL
viewState={this.state.viewport}
layers={[layer]}
getCursor={() => 'initial'}
{...(layerType === 'polygonLayer'
? {
getTooltip: ({ object }) => object && {
html: `
<h2>${object.prefLabel}</h2>
<div>${object.instanceCount}</div>
`
// style: {
// backgroundColor: '#f00',
// fontSize: '0.8em'
// }
}
}
: {})
}
/>
{this.renderSpinner()}
{layerType === 'arcLayer' && this.props.instanceAnalysisData && this.state.dialog.open &&
<DeckArcLayerDialog
onClose={this.closeDialog.bind(this)}
data={this.props.instanceAnalysisData}
from={this.state.dialog.from}
to={this.state.dialog.to}
fromText={this.props.fromText}
toText={this.props.toText}
countText={this.props.countText}
listHeadingSingleInstance={this.props.listHeadingSingleInstance}
listHeadingMultipleInstances={this.props.listHeadingMultipleInstances}
instanceVariable={[this.props.instanceVariable]}
resultClass={this.props.resultClass}
facetClass={this.props.facetClass}
/>}
{layerType === 'arcLayer' && showTooltip &&
<DeckArcLayerTooltip
data={hoverInfo}
fromText={this.props.fromText}
toText={this.props.toText}
countText={this.props.countText}
showMoreText={this.props.showMoreText}
/>}
</ReactMapGL>
</div>
)
}
Example #6
Source File: index.js From covid-trials-dashboard with MIT License | 4 votes |
Map = ({ pins, handleSelectedId }) => {
const {
state: { prefersDarkMode },
} = useContext(store) || { state: { prefersDarkMode: false } }
const [popUp, setPopUp] = useState()
const [viewport, setViewport] = useState({
latitude: 40.67,
longitude: -73.94,
zoom: 0.8,
bearing: 0,
pitch: 0,
})
useEffect(() => {
if (typeof navigator !== 'undefined' && 'geolocation' in navigator) {
navigator.geolocation.getCurrentPosition(
location => {
setViewport({
latitude: location.coords.latitude,
longitude: location.coords.longitude,
altitude: location.coords.altitude,
zoom: 9,
})
},
error => {
console.log('User did not allow location', error)
}
)
}
}, [])
const PinComponent = useMemo(() => {
const onClick = popupInfo => {
setPopUp(popupInfo)
handleSelectedId(popupInfo.productId)
}
return (
<Pins data={pins} onClick={onClick} handleSelectedId={handleSelectedId} />
)
}, [pins, handleSelectedId])
const PopUpComponent = useMemo(() => {
const onClose = () => {
setPopUp(null)
handleSelectedId('clear')
}
return (
<>
<PopUpDisplay popupInfo={popUp} onClose={onClose} />
</>
)
}, [popUp, handleSelectedId])
const Controls = useMemo(() => {
return (
<>
<FullscreenControlDiv>
<FullscreenControl />
</FullscreenControlDiv>
<NavDiv>
<NavigationControl />
</NavDiv>
<ScaleControlDiv>
<ScaleControl />
</ScaleControlDiv>
</>
)
}, [])
return (
<ReactMapGL
{...viewport}
onViewportChange={nextViewport => setViewport(nextViewport)}
mapStyle={
prefersDarkMode
? 'mapbox://styles/mapbox/dark-v10?optimize=true'
: 'mapbox://styles/adibi2011/ckgtx36fp09lk19n2csgrxnu4'
}
mapboxApiAccessToken={mapboxApiKey}
width='100%'
height='100%'
>
{PinComponent}
{PopUpComponent}
{Controls}
</ReactMapGL>
)
}
Example #7
Source File: Chloropleth.jsx From covince with MIT License | 4 votes |
Chloropleth = (props) => {
const {
color_scale_type,
config = {},
darkMode = false,
enable_fade_uncertainty,
geojson,
handleOnClick,
lineColor = 'blueGray',
max_val,
min_val,
parameterConfig,
selected_area,
values
} = props
const isBig = useMediaQuery('(min-width: 2160px)')
const defaultZoom = useMemo(() => {
const { default_zoom, default_zoom_mob = default_zoom } = config
if (typeof default_zoom === 'number') {
return props.isMobile ? default_zoom_mob : default_zoom
}
const { desktop, mobile = desktop, big = desktop } = default_zoom
if (props.isMobile) return mobile
if (isBig) return big
return desktop
}, [config, props.isMobile, isBig])
const [query, updateQuery] = useQueryAsState({
...mapViewportToQuery({
latitude: config.default_lat,
longitude: config.default_lon,
zoom: defaultZoom,
pitch: 0,
bearing: 0
}),
uncertainty: '1'
})
const [viewport, setViewport] = useState({
width: 0,
height: 0,
...mapQueryToViewport(query, config.bounds)
})
// for bounds checking
// const vp = new WebMercatorViewport(viewport)
// console.log(vp.getBounds())
useEffect(() => {
setViewport({ ...viewport, ...mapQueryToViewport(query, config.bounds) })
}, getDependencyArray(query))
useEffect(() => {
const timeout = setTimeout(() => {
const update = mapViewportToQuery(viewport)
if (doesNotMatch(update, query)) {
updateQuery(update, 'replace')
}
}, 500)
return () => clearTimeout(timeout)
}, getDependencyArray(viewport))
const onViewportChange = newViewport => {
clampViewport(newViewport, config.bounds)
setViewport(newViewport)
}
const percentage = parameterConfig && parameterConfig.format === 'percentage'
const hasUncertainty = useMemo(() => {
if (enable_fade_uncertainty !== undefined) return enable_fade_uncertainty
if (percentage) { // back compat
for (const v of Object.values(values)) {
if (v === undefined) return false
const { upper, lower } = v
if (upper !== null && lower !== null && upper !== lower) {
return true
}
}
}
return false
}, [enable_fade_uncertainty, values, percentage])
const features = useMemo(() => {
const features = {
selected: [],
active: [],
nulls: [],
others: []
}
if (values === null) {
return features
}
for (const feature of geojson.features) {
const { area_id } = feature.properties
const areaValues = values[area_id] || {}
if (areaValues.mean !== undefined) {
features.nulls.push(feature) // white bg for alpha and smoother dark mode
if (area_id === selected_area) features.selected.push(feature)
const { mean, lower, upper } = areaValues
if (mean !== null) {
const _feature = {
...feature,
properties: {
...feature.properties,
value: mean,
alpha: hasUncertainty ? 1 - (upper - lower) : 1
}
}
features.active.push(_feature)
}
} else {
features.others.push(feature)
}
}
return features
}, [geojson, values, selected_area, hasUncertainty])
const colorScale = useMemo(() => {
if (max_val === 0) {
return [0, '#fff']
}
const stops = color_scale_type === 'R_scale' ? RColourStops : colourStops
const scale = []
const min = color_scale_type === 'quadratic' ? Math.sqrt(min_val) : min_val
const max = color_scale_type === 'quadratic' ? Math.sqrt(max_val) : max_val
const range = max - min
for (const { index, rgb } of stops) {
scale.unshift(rgb)
scale.unshift(min + range * (1 - index))
}
return scale
}, [max_val, min_val, color_scale_type])
const showUncertainty = useMemo(() => query.uncertainty === '1', [query.uncertainty])
const mapStyle = useMemo(() => ({
version: 8,
transition: {
duration: 0
},
sources: {
selectedAreas: {
type: 'geojson',
data: {
...geojson,
features: features.selected
}
},
activeAreas: {
type: 'geojson',
data: {
...geojson,
features: features.active
}
},
nullAreas: {
type: 'geojson',
data: {
...geojson,
features: features.nulls
}
},
otherAreas: {
type: 'geojson',
data: {
...geojson,
features: features.others
}
}
},
layers: [
{
id: 'other-areas-fill',
type: 'fill',
source: 'otherAreas',
paint: {
'fill-color': darkMode ? tailwindColors[lineColor][300] : '#fff'
}
},
{
id: 'other-areas-line',
type: 'line',
source: 'otherAreas',
paint: {
'line-color': tailwindColors[lineColor][darkMode ? 400 : 300],
'line-width': 0.5
}
},
{
id: 'null-areas-fill',
type: 'fill',
source: 'nullAreas',
paint: {
'fill-color': '#fff'
}
},
{
id: 'null-areas-line',
type: 'line',
source: 'nullAreas',
paint: {
'line-color': tailwindColors[lineColor][500],
'line-width': 0.5
}
},
{
id: 'active-areas-fill',
type: 'fill',
source: 'activeAreas',
paint: {
'fill-color': [
'interpolate',
['linear'],
color_scale_type === 'quadratic'
? ['sqrt', ['get', 'value']]
: ['get', 'value'],
...colorScale
],
'fill-opacity': showUncertainty ? ['get', 'alpha'] : 1
}
},
{
id: 'active-areas-line',
type: 'line',
source: 'activeAreas',
paint: {
'line-color': tailwindColors[lineColor][600],
'line-width': 0.5
}
},
{
id: 'selected-areas-line',
type: 'line',
source: 'selectedAreas',
paint: {
'line-color': tailwindColors[lineColor][900],
'line-width': 2
}
}
]
}), [features, colorScale, color_scale_type, showUncertainty, darkMode, lineColor])
const [hoveredFeature, setHoveredFeature] = useState(null)
const hoverPopup = useMemo(() => {
if (hoveredFeature === null) return null
const { area_id, area_name, lat, long } = hoveredFeature.properties
const value = values[area_id]
if (area_id in values) {
return { lat, long, value, label: area_name, onClick: () => handleOnClick(area_id) }
}
}, [hoveredFeature, values, handleOnClick])
const colourBarOpacity = useMemo(() => {
if (hasUncertainty && showUncertainty) {
return 0.666
// let sum = 0
// for (const { properties } of features.active) {
// sum += properties.alpha
// }
// return sum / features.active.length
}
return 1
}, [hasUncertainty, showUncertainty, features.active])
return (
<Measure
bounds
onResize={rect => {
setViewport({
...viewport,
width: rect.bounds.width || viewport.width,
height: rect.bounds.height || viewport.height
})
}}
>
{({ measureRef }) => (
<div ref={measureRef} className={classnames(props.className, 'relative z-0')}>
<ReactMapGL
{...viewport}
minZoom={config.min_zoom}
disableTokenWarning
onViewportChange={onViewportChange}
mapStyle={mapStyle}
mapboxApiUrl={null}
className='bg-gray-50 dark:bg-gray-600'
interactiveLayerIds={['null-areas-fill', 'active-areas-fill']}
onNativeClick={e => { // faster for some reason
const [feature] = e.features
if (!feature) {
handleOnClick('overview')
} else {
handleOnClick(feature.properties.area_id)
}
}}
onHover={e => {
const [feature] = e.features
if (feature && feature.properties.value !== 'null') {
if (feature.properties.lat === undefined) {
// Hack where if no central point is specified
// we use mouse position for popup
feature.properties.lat = e.lngLat[1]
feature.properties.long = e.lngLat[0]
}
setHoveredFeature(feature)
} else {
setHoveredFeature(null)
}
}}
getCursor={({ isHovering, isDragging }) => {
if (isDragging) return 'grabbing'
if (isHovering || selected_area !== 'overview') return 'pointer'
return 'grab'
}}
// onLoad={(e) => {
// // if (initialBounds) {
// // e.target.fitToBounds(initialBounds)
// // }
// }}
>
<NavigationControl className='right-2 top-2 z-10' />
{ hoverPopup && <MapPopup {...hoverPopup} {...parameterConfig} /> }
</ReactMapGL>
<FadeTransition in={max_val > 0}>
<div className='absolute left-0 bottom-0 w-60 z-10 p-2 pb-0 bg-white dark:bg-gray-700 bg-opacity-80 dark:bg-opacity-80'>
{ hasUncertainty &&
<form className='mb-1.5 ml-2'>
<Checkbox
id='map_uncertainty'
className='text-primary'
checked={showUncertainty}
onChange={e => updateQuery({ uncertainty: e.target.checked ? 1 : 0 }, 'replace')}
>
<span className='text-xs tracking-wide select-none'>
fade areas by uncertainty
</span>
</Checkbox>
</form> }
<ColourBar
dmin={min_val}
dmax={max_val}
type={color_scale_type}
percentage={percentage}
opacity={colourBarOpacity}
/>
</div>
</FadeTransition>
</div>
)}
</Measure>
)
}