Skip to content

Instantly share code, notes, and snippets.

@slaskis
Created April 3, 2017 06:04
Show Gist options
  • Save slaskis/615ea6c3781683ce8a9555df4f662f74 to your computer and use it in GitHub Desktop.
Save slaskis/615ea6c3781683ce8a9555df4f662f74 to your computer and use it in GitHub Desktop.
import "./App.css";
import { Component, h } from "preact";
import {
SearchkitManager,
SearchkitProvider,
RefinementListFilter,
Layout,
TopBar,
LayoutBody,
LayoutResults,
ActionBar,
ActionBarRow,
SideBar
} from "searchkit";
const searchkit = new SearchkitManager(
""
);
export default class App extends Component {
componentDidMount() {
mapboxgl.accessToken = "";
this.map = new mapboxgl.Map({
container: this.viewport,
style: "mapbox://styles/mapbox/streets-v9"
});
this.map.on("load", this.onMapReady);
this.map.on("resize", this.onMapChange);
this.map.on("moveend", this.onMapChange);
// inject a bounds query
searchkit.setQueryProcessor(plainQueryObject => {
console.log("query object", plainQueryObject);
const bounds = this.map.getBounds();
if (bounds) {
const clampGeo = ([lat, lng]) => {
return [
Math.min(Math.max(lat, -90), 90),
Math.min(Math.max(lng, -180), 180)
];
};
const newQuery = {
bool: {
must: { match_all: {} },
filter: {
geo_bounding_box: {
type: "indexed",
location: {
top_left: clampGeo(bounds.getNorthWest().toArray()),
bottom_right: clampGeo(bounds.getSouthEast().toArray())
}
}
}
}
};
plainQueryObject.query = newQuery;
plainQueryObject.size = 1000;
}
return plainQueryObject;
});
}
componentWillUnmount() {
this.map.off("load", this.onMapChange);
this.map.off("resize", this.onMapChange);
this.map.off("moveend", this.onMapChange);
this.offResults();
}
onFormUpdate = formState => {
console.log("form change", formState);
};
onMapReady = () => {
const geojson = {
type: "FeatureCollection",
features: []
};
this.map.addSource("coordinates-data", {
type: "geojson",
data: geojson
});
this.map.addLayer({
id: "coordinates",
type: "circle",
source: "coordinates-data"
});
this.offResults = searchkit.addResultsListener(results => {
console.log("got results", results);
if (results.hits && results.hits.hasChanged) {
geojson.features = results.hits.hits.map(hit => ({
type: "Feature",
properties: {},
geometry: {
type: "Point",
coordinates: hit._source.location
.split(/\s*,\s*/)
.map(Number)
.reverse()
}
}));
this.map.getSource("coordinates-data").setData(geojson);
}
});
};
onMapChange = () => {
console.log("map change");
console.log(" - bounds:", this.map.getBounds());
searchkit.reloadSearch();
};
render() {
return (
<SearchkitProvider searchkit={searchkit}>
<Layout>
<LayoutBody>
<SideBar>
<RefinementListFilter
field="device_id"
title="Device"
id="device_id"
/>
</SideBar>
<LayoutResults>
<div
ref={el => this.viewport = el}
style={{ width: "100%", height: "100%" }}
/>
</LayoutResults>
</LayoutBody>
</Layout>
</SearchkitProvider>
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment