libre-charge-map/js/main_2.js
2024-10-17 23:57:47 +02:00

288 lines
8.5 KiB
JavaScript

//import * as geoDataPointsFromApi from './data.json';
const overrideQuery = true
const initialZoom = 14
const maxZoom = 21
const startCenterCoordinates = []
const osmMention = '&copy; <a href="https://openstreetmap.org/copyright">OpenStreetMap</a> contributors'
const baseUrl = 'https://overpass-api.de/api/interpreter'
// serveurs de tuiles: https://wiki.openstreetmap.org/wiki/Tile_servers
// https://stamen-tiles.a.ssl.fastly.net/toner/{z}/{x}/{y}.png
// https://a.tile.openstreetmap.fr/osmfr/{z}/{x}/{y}.png
const tileServer = 'https://cartodb-basemaps-{s}.global.ssl.fastly.net/light_all/{z}/{x}/{y}.png'
/**
* config des couches de fond de carte
*/
// var osm = L.tileLayer(
// tileServer, {
// maxZoom: maxZoom,
// attribution: '© OpenStreetMap'
// })
//
// var osmHOT = L.tileLayer('https://{s}.tile.openstreetmap.fr/hot/{z}/{x}/{y}.png', {
// maxZoom: maxZoom,
// attribution: '© OpenStreetMap contributors, Tiles style by Humanitarian OpenStreetMap Team hosted by OpenStreetMap France'
// })
// var openTopoMap = L.tileLayer('https://{s}.tile.opentopomap.org/{z}/{x}/{y}.png', {
// maxZoom: 19,
// attribution: 'Map data: © OpenStreetMap contributors, SRTM | Map style: © OpenTopoMap (CC-BY-SA)'
// })
// Créer la carte centrée sur Rouen
// const map = L.map('map', {
// center: startCenterCoordinates,
// zoom: initialZoom,
// layers: [
// // osm,
// osmHOT,
// // openTopoMap
// ],
// })
const map = L.map('map').setView(startCenterCoordinates, initialZoom)
// let circle = L.circle(startCenterCoordinates, {
// color: 'green',
// fillColor: '#f03',
// fillOpacity: 0.5,
// radius: 10
// }).addTo(map)
// var baseMaps = {
// 'OpenStreetMap': osm,
// 'OpenStreetMap.HOT': osmHOT
// }
// exemple de markers à grouper
// var crownHill = L.marker([39.75, -105.09]).bindPopup('This is Crown Hill Park.'),
// rubyHill = L.marker([39.68, -105.00]).bindPopup('This is Ruby Hill Park.')
// var cities = L.layerGroup([crownHill])
// var parks = L.layerGroup([crownHill, rubyHill])
//
// var overlayMaps = {
// 'Cities': cities
// }
//
// var layerControl = L.control.layers(baseMaps, overlayMaps).addTo(map)
// layerControl.addBaseLayer(openTopoMap, 'OpenTopoMap')
// layerControl.addOverlay(parks, '+150kW')
function initMap (callback) {
// Créer un groupe de couches pour les marqueurs de type 2
// var type2Markers = L.layerGroup()
// L.tileLayer(tileServer, {
// maxZoom,
// attribution: osmMention,
// }).addTo(map)
// Ajouter les marqueurs de type 2 au groupe de couches
// map.eachLayer(function (layer) {
// if (layer.feature) {
// if (layer.feature?.properties?.tags['socket:type2']) {
// type2Markers.addLayer(layer)
// console.log('includes', layer.feature.properties.tags['socket:type2'])
// }
//
// }
// })
// Ajouter le groupe de couches aux couches de la carte
// map.addLayer(type2Markers)
// Ajouter un interrupteur pour afficher ou masquer les marqueurs de type 2
// var type2Toggle = L.control({ position: 'topright' })
// type2Toggle.onAdd = function (map) {
// var div = L.DomUtil.create('div', 'leaflet-bar leaflet-control leaflet-control-custom')
// div.innerHTML = '<input type="checkbox" id="type2-toggle" checked><label for="type2-toggle">Afficher Type 2</label>'
// L.DomEvent.on(document, 'click', function () {
// type2Markers.setVisible(document.getElementById('type2-toggle').checked)
// })
// return div
// }
// map.addControl(type2Toggle)
}
function buildOverpassApiUrl (map, overpassQuery) {
var bounds = map.getBounds().getSouth() + ',' + map.getBounds().getWest() + ',' + map.getBounds().getNorth() + ',' + map.getBounds().getEast()
var resultUrl, query = ''
if (overrideQuery) {
query = `?data=[out:json][timeout:15];(
node[amenity=charging_station](${bounds});
);out body geom;`
} else {
var nodeQuery = 'node[' + overpassQuery + '](' + bounds + ');'
var wayQuery = 'way[' + overpassQuery + '](' + bounds + ');'
var relationQuery = 'relation[' + overpassQuery + '](' + bounds + ');'
query = '?data=[out:json][timeout:15];(' + nodeQuery + wayQuery + relationQuery + ');out body geom;'
}
resultUrl = baseUrl + query
console.log('resultUrl', resultUrl)
return resultUrl
}
const tags_to_display_in_popup = ['capacity', 'socket:type_2',
'socket:type2:output',
'charging_station:output',
'socket:typee',
'socket:type2_combo',
'socket:chademo',
'operator',
'ref:EU:EVSE',
'network',
'contact',
'phone']
function supprimerMarqueurs (map) {
map.eachLayer(function (layer) {
if (layer instanceof L.Marker) {
map.removeLayer(layer)
}
})
}
function displayPointsFromApi (points) {
// supprimerMarqueurs()
var resultAsGeojson = osmtogeojson(points)
console.log('resultAsGeojson', resultAsGeojson)
var resultLayer = L.geoJson(resultAsGeojson, {
style: function (feature) {
return { color: '#f00' }
},
// filter: function (feature, layer) {
// var isPolygon = (feature.geometry) && (feature.geometry.type !== undefined) && (feature.geometry.type === 'Polygon')
// if (isPolygon) {
// feature.geometry.type = 'Point'
// var polygonCenter = L.latLngBounds(feature.geometry.coordinates[0]).getCenter()
// feature.geometry.coordinates = [polygonCenter.lat, polygonCenter.lng]
// }
// return true
// },
// onzoomend: function (event) {
// console.log('event zoom end', event)
// },
onEachFeature: function (feature, layer) {
var popupContent = ''
console.log('feature.properties', feature.properties)
// var keys = Object.keys(feature.properties.tags)
// ne montrer que certains champs dans la popup
// tags_to_display_in_popup.forEach(function (key) {
// if (tags_to_display_in_popup.indexOf(key)) {
// let value = feature.properties.tags[key]
// if (value) {
// popupContent = popupContent + '<br/><strong class="popup-key">' + key + ' :</strong> ' + value + ''
// }
// }
// })
// popupContent = popupContent + '</dl>'
// layer.bindPopup(popupContent)
//
// let iconSiZePx = 20
//
// let rest_name = ''
//
// let html = '<a class="edit-button" href="https://www.openstreetmap.org/edit?editor=id&node=' + feature.properties.id + '">' +
// '✏️</a> <br/>' + popupContent
console.log('layer', layer)
// var label = L.marker(layer._latlng, {
// icon: L.divIcon({
// iconUrl: '/img/socket_type2svg',
// // + getIconFromTags(feature.properties.tags),
// className: 'label ' + makeCssClassFromTags(feature.properties.tags),
// // ,
// iconSize: ['auto', 'auto'],
// }),
// }).addTo(map)
// ajout de cercle coloré selon la puissance
// var myIcon = L.icon({
// iconUrl: 'https://cipherbliss.com/ou-manger/img/' + getIconFromTags(feature.properties.tags),
// iconSize: [iconSiZePx, iconSiZePx],
// iconAnchor: [iconSiZePx / 2, iconSiZePx / 2],
// popupAnchor: [iconSiZePx / 2, iconSiZePx / 2],
// className: makeCssClassFromTags(feature.properties.tags),
//
// })
// let regular_marker = L.marker(layer._latlng, { title: rest_name, icon: myIcon }).addTo(map)
// regular_marker.bindPopup(html)
// regular_marker.on({
// mouseover: function () {
// this.openPopup()
// },
// mouseout: function () {
// setTimeout(() => this.closePopup(), 3000)
// },
// click: function () {
// this.openPopup()
// },
// })
},
})
}
function makeCssClassFromTags (tags) {
console.log('tags', tags)
let tagKeys = Object.keys(tags)
console.log('tagKeys', tagKeys)
if (!tags) {
return ''
}
let listOfClasses = []
tagKeys.forEach((element) => {
listOfClasses.push('tag-' + element + '_' + tags[element].replace(':', '--').replace(' ', '-'))
})
return listOfClasses.join(' ')
}
function getIconFromTags (tags) {
let iconFileName = ''
// let iconFileName = 'icon_restaurant.png';
if (tags['socket:type_2'] == '150 kW') {
iconFileName = 'fountain.png'
}
return iconFileName
}
$('#query-button').click(function () {
loadOverpassQuery()
})
let isLoading = false
function loadOverpassQuery () {
console.log('load data')
// ne pas charger si on recherche déjà
if (!isLoading) {
isLoading = true
$('#spinning_icon').fadeIn()
var queryTextfieldValue = $('#query-textfield').val()
console.log('queryTextfieldValue', queryTextfieldValue)
var overpassApiUrl = buildOverpassApiUrl(map, queryTextfieldValue)
$.get(overpassApiUrl, function (geoDataPointsFromApi) {
displayPointsFromApi(geoDataPointsFromApi)
$('#spinning_icon').fadeOut()
isLoading = false
}) // end of the getting from overpass API
}
}
// initMap()
// $('#spinning_icon').hide()
// loadOverpassQuery()