/map_controller.js Secret
Created
March 21, 2024 01:31
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Controller } from "stimulus"; | |
import mapboxgl from "mapbox-gl"; | |
import "mapbox-gl/dist/mapbox-gl.css"; | |
export default class extends Controller { | |
static values = { offices: String, center: String }; | |
connect() { | |
mapboxgl.accessToken = ""; | |
let map = new mapboxgl.Map({ | |
container: "map", | |
attributionControl: true, | |
style: "mapbox://styles/mapbox/satellite-streets-v11", | |
}); | |
map.on("load", function () { | |
map.resize(); | |
}); | |
map.addControl(new mapboxgl.NavigationControl()); | |
let addresses = JSON.parse(this.officesValue); | |
let bounds = new mapboxgl.LngLatBounds(); | |
addresses.forEach(function (address) { | |
bounds.extend([address.longitude, address.latitude]); | |
new mapboxgl.Marker() | |
.setLngLat([address.longitude, address.latitude]) | |
.setPopup( | |
new mapboxgl.Popup().setHTML( | |
`<em>${address.company.name}</em><br/> | |
<address>${address.street}<br/>${address.city}, ${ | |
address.state | |
}</address> | |
${address.primary_contact?.first_name || ""} ${ | |
address.primary_contact?.last_name || "" | |
}<br/> | |
${address.primary_contact?.email || ""}<br/> | |
${address.primary_contact?.phone_number || ""}` | |
) | |
) | |
.addTo(map); | |
}); | |
if (this.centerValue) { | |
new mapboxgl.Marker({ color: "#dc3545" }) | |
.setLngLat(JSON.parse(this.centerValue)) | |
.addTo(map); | |
} | |
map.fitBounds(bounds, { padding: 100 }); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<div class="col h-75" data-controller="map" data-map-offices-value="<%= @offices.to_json(methods: [:address]) %>"> | |
<div class="w-100 h-100" id="map"> | |
</div> | |
</div> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment