Skip to content

Commit

Permalink
Add geocode
Browse files Browse the repository at this point in the history
  • Loading branch information
cristineguadelupe committed Jan 12, 2024
1 parent 4ac6d78 commit a36e362
Show file tree
Hide file tree
Showing 3 changed files with 103 additions and 1 deletion.
57 changes: 57 additions & 0 deletions lib/assets/maplibre/main.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,17 @@
import "https://cdn.jsdelivr.net/npm/[email protected]/dist/maplibre-gl.min.js";
// TODO: point to npm when released
import "https://cdn.jsdelivr.net/gh/jimmyrocks/maplibre-gl-vector-text-protocol@main/dist/maplibre-gl-vector-text-protocol.min.js";
import "https://cdn.jsdelivr.net/npm/@maplibre/[email protected]/dist/maplibre-gl-geocoder.min.js";

export function init(ctx, data) {
ctx.importCSS(
"https://cdn.jsdelivr.net/npm/[email protected]/dist/maplibre-gl.min.css"
);

ctx.importCSS(
"https://cdn.jsdelivr.net/npm/@maplibre/[email protected]/lib/maplibre-gl-geocoder.min.css"
);

ctx.root.innerHTML = `
<div id='map' style='width: 896px; height: 400px;'></div>
`;
Expand All @@ -19,6 +24,7 @@ export function init(ctx, data) {
controls = [],
locate = [],
terrain = [],
geocode = [],
hover = [],
center = [],
info = [],
Expand Down Expand Up @@ -46,6 +52,9 @@ export function init(ctx, data) {
terrain.forEach(() => {
addTerrain();
});
geocode.forEach(() => {
addGeocode();
});
hover.forEach((layer) => {
addHover(layer);
});
Expand Down Expand Up @@ -88,6 +97,10 @@ export function init(ctx, data) {
addTerrain();
});

ctx.handleEvent("add_geocode", () => {
addGeocode();
});

ctx.handleEvent("clusters_expansion", (clusters) => {
inspectClusters(clusters);
});
Expand Down Expand Up @@ -143,6 +156,10 @@ export function init(ctx, data) {
map.addControl(terrain);
}

function addGeocode() {
map.addControl(geocoder());
}

function loadImage({ name, url, options }) {
map.loadImage(url, (error, image) => {
if (error) throw error;
Expand Down Expand Up @@ -220,4 +237,44 @@ export function init(ctx, data) {
map.getCanvas().style.cursor = "";
});
}

function geocoder() {
const geocoderApi = {
forwardGeocode: async (config) => {
const features = [];
try {
const request = `https://nominatim.openstreetmap.org/search?q=${config.query}&format=geojson&polygon_geojson=1&addressdetails=1`;
const response = await fetch(request);
const geojson = await response.json();
for (const feature of geojson.features) {
const center = [
feature.bbox[0] + (feature.bbox[2] - feature.bbox[0]) / 2,
feature.bbox[1] + (feature.bbox[3] - feature.bbox[1]) / 2,
];
const point = {
type: "Feature",
geometry: {
type: "Point",
coordinates: center,
},
place_name: feature.properties.display_name,
properties: feature.properties,
text: feature.properties.display_name,
place_type: ["place"],
center,
};
features.push(point);
}
} catch (e) {
console.error(`Failed to forwardGeocode with error: ${e}`);
}

return {
features,
};
},
};

return new MaplibreGeocoder(geocoderApi, { maplibregl });
}
}
18 changes: 18 additions & 0 deletions lib/kino/maplibre.ex
Original file line number Diff line number Diff line change
Expand Up @@ -220,6 +220,18 @@ defmodule Kino.MapLibre do
update_events(map, :terrain, %{})
end

@doc """
Adds a geocoder control to the map to handle Nominatim queries
## Examples
Kino.MapLibre.add_geocode(map)
"""
@spec add_geocode(maplibre()) :: :ok | %__MODULE__{}
def add_geocode(map) do
update_events(map, :geocode, %{})
end

@doc """
A helper function to allow inspect a cluster on click. Receives the ID of the clusters layer
## Examples
Expand Down Expand Up @@ -342,6 +354,12 @@ defmodule Kino.MapLibre do
{:noreply, ctx}
end

def handle_cast({:geocode, geocode}, ctx) do
broadcast_event(ctx, "add_geocode", geocode)
ctx = update_assigned_events(ctx, :geocode, geocode)
{:noreply, ctx}
end

def handle_cast({:hover, layer}, ctx) do
broadcast_event(ctx, "add_hover", layer)
ctx = update_assigned_events(ctx, :hover, layer)
Expand Down
29 changes: 28 additions & 1 deletion test/kino/maplibre_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -223,7 +223,7 @@ defmodule Kino.MapLibreTest do
assert ml.events.terrain == [%{}]
end

test "adds a geolocate control to a dynamic map" do
test "adds a terrain control to a dynamic map" do
ml = Ml.new() |> Kino.MapLibre.new()
Kino.MapLibre.add_terrain(ml)
data = connect(ml)
Expand All @@ -244,6 +244,33 @@ defmodule Kino.MapLibreTest do
end
end

describe "add_geocode/1" do
test "adds a geocode control to a static map" do
ml = Ml.new() |> Kino.MapLibre.add_geocode()
assert ml.events.geocode == [%{}]
end

test "adds a geocode control to a dynamic map" do
ml = Ml.new() |> Kino.MapLibre.new()
Kino.MapLibre.add_geocode(ml)
data = connect(ml)

assert data.events.geocode == [%{}]

assert_broadcast_event(ml, "add_geocode", %{})
end

test "adds a geocode control to a converted map" do
ml = Ml.new() |> Kino.MapLibre.add_geocode() |> Kino.MapLibre.new()
Kino.MapLibre.add_geocode(ml)
data = connect(ml)

assert data.events.geocode == [%{}, %{}]

assert_broadcast_event(ml, "add_geocode", %{})
end
end

describe "clusters_expansion/2" do
test "adds a cluster expansion to a static map" do
ml = Ml.new() |> Kino.MapLibre.clusters_expansion("clusters")
Expand Down

0 comments on commit a36e362

Please sign in to comment.