Skip to content

Instantly share code, notes, and snippets.

@ohoroyoi
Created August 28, 2019 09:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ohoroyoi/97e14a015544822bfa305a741b69104a to your computer and use it in GitHub Desktop.
Save ohoroyoi/97e14a015544822bfa305a741b69104a to your computer and use it in GitHub Desktop.
leaflet 클릭하면 마커에 포커싱하게 하는것 (과정)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Leaflet tutorial</title>
</head>
<body>
<script
src="https://code.jquery.com/jquery-2.2.4.js"
integrity="sha256-iT6Q9iMJYuQiMWNd9lDyBUStIq/8PuOW33aOqmvFpqI="
crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/leaflet.draw/1.0.4/leaflet.draw.css"/>
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.5.1/dist/leaflet.css"
integrity="sha512-xwE/Az9zrjBIphAcBb3F6JVqxf46+CDLwfLMHloNu6KEQCAWi6HcDUbeOfBIptF7tcCzusKFjFw2yuvEpDL9wQ=="
crossorigin=""/>
<script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<script src="https://unpkg.com/leaflet@1.5.1/dist/leaflet.js"
integrity="sha512-GffPMF3RvMeYyc1LWMHtK8EbPv0iNZ8/oTtHPx9/cc2ILxQ+u905qIwdpULaqDkyBKgOaB57QTMg7ztg8Jm2Og=="
crossorigin=""></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet.draw/1.0.4/leaflet.draw.js"></script>
<style>
body {
margin: 0;
padding: 0;
}
#map {
position: absolute;
top: 0;
bottom: 0;
width: 100%;
height: 500px;
}
#apicall, #export {
position: absolute;
top:50px;
right:10px;
z-index:3000;
background:white;
color:black;
padding:6px;
border-radius:4px;
font-family: 'Helvetica Neue';
cursor: pointer;
font-size:12px;
text-decoration:none;
}
.leaflet-top {
top: 100px;
}
#export {
top:10px;
}
#clicked_region {
position: absolute;
top: 500px;
}
#aoi_table {
position: absolute;
top: 550px;
}
td {
background-color: rgb(243, 243, 244);
}
</style>
<div class="row">
<div id="map"></div>
<div id="apicall">Api로 DB에 저장</div>
<a href='#' id='export'>Export Features</a>
<div id="clicked_region">Clicked Region</div>
<table id="aoi_table" class="table table-hover data-table">
<thead>
<tr>
<th>code</th>
<th>coordinates</th>
<th>data</th>
</tr>
</thead>
<tbody>
<tr role="row" class="odd"><td class="sorting_1">{"custom_region_info":{"type":"FeatureCollection","features":[{"geometry":{"coordinates":[127.030812,37.504279],"type":"Point"},"type":"Feature","properties":{"name":"gangnam","shapeContinent":"AS","detail":"강남스타일","shapeCountry":"KR"}}]},"custom_region_detail":"gangnam style"}</td><td>[127.030812,37.504279]</td><td>false</td></tr><tr role="row" class="even"><td class="sorting_1">{"custom_region_info":{"type":"FeatureCollection","features":[{"geometry":{"coordinates":[127.339084,36.780266],"type":"Point"},"type":"Feature","properties":{"name":"matzip00","shapeContinent":"AS","detail":"맛집아입니까","shapeCountry":"KR"}}]},"custom_region_detail":"맛집아입니까"}</td><td>[127.339084,36.780266]</td><td>false</td></tr><tr role="row" class="odd"><td class="sorting_1">{"custom_region_info":{"type":"FeatureCollection","features":[{"geometry":{"coordinates":[127.717858,37.290286],"type":"Point"},"type":"Feature","properties":{"name":"ggg","shapeContinent":"AS","detail":"킹갓제너럴","shapeCountry":"KR"}}]},"custom_region_detail":"킹갓제너럴"}</td><td>[127.717858,37.290286]</td><td>false</td></tr><tr role="row" class="even"><td class="sorting_1">{"custom_region_info":{"type":"FeatureCollection","features":[{"geometry":{"coordinates":[[[126.858317,37.508788],[126.892971,37.527337],[126.915682,37.517666],[126.906669,37.484818],[126.87527,37.488712],[126.858317,37.508788]]],"type":"Polygon"},"type":"Feature","properties":{"name":"gaebal","shapeContinent":"AS","detail":"ww","shapeCountry":"KR"}}]},"custom_region_detail":"ww"}</td><td>[[[126.858317,37.508788],[126.892971,37.527337],[126.915682,37.517666],[126.906669,37.484818],[126.87527,37.488712],[126.858317,37.508788]]]</td><td>false</td></tr><tr role="row" class="odd"><td class="sorting_1">{"custom_region_info":{"type":"FeatureCollection","features":[{"geometry":{"coordinates":[[[126.978624,37.543081],[126.988227,37.537689],[127.009053,37.540406],[127.014608,37.553181],[126.988681,37.559803],[126.978624,37.543081]]],"type":"Polygon"},"type":"Feature","properties":{"name":"namsango","shapeContinent":"AS","detail":"남산가자","shapeCountry":"KR"}}]},"custom_region_detail":"남산가자"}</td><td>[[[126.978624,37.543081],[126.988227,37.537689],[127.009053,37.540406],[127.014608,37.553181],[126.988681,37.559803],[126.978624,37.543081]]]</td><td>false</td></tr></tbody>
</table>
</div>
<script>ATLAS_ADMIN_HOST = "http://localhost:8088";</script>
<script>
$("#aoi_table").on("click", "td", function() {
alert($( this ).text());
if($(this).index() === 1) { // coordinates 줄을 클릭했을때만 실행 되도록
centerLeafletMapOnMarker(map, JSON.parse($( this ).text()));
}
});
function centerLeafletMapOnMarker(map, latLngs) {
console.log("좌표: ", latLngs);
console.log("좌표 길이 : ", latLngs.length);
if (latLngs.length == 1) {
// 폴리곤의 좌표
} else if (latLngs.length == 2) {
// 마커의 좌표
console.log("마커의 좌표 : ", latLngs);
// map.setView(latLngs, 2); bounds로 해야하나보네 ㅠ
var [l, r] = latLngs;
console.log("left : ", l);
console.log("right: ", r);
var southWest = L.latLng(l, r);
var northEast = L.latLng(l+0.062, r+0.102);
console.log("southWest : ", southWest);
console.log("northEast : ", northEast);
var bounds = L.latLngBounds(southWest, northEast);
// map.setView(bounds, 11, { animation: true });
map.flyTo([l, r], 13);
// map.fitBounds(bounds);
// map.fitBounds([
// [l, r],
// [l+0.062, r-0.102]
// ]);
// https://leafletjs.com/reference-1.0.0.html#latlngbounds
} else {
}
// var corner1 = L.latLng(40.712, -74.227),
// corner2 = L.latLng(40.774, -74.125),
// bounds = L.latLngBounds(corner1, corner2);
// map.fitBounds(bounds);
}
function createDataTable() {
var tableId = "aoi_table";
$('#' + tableId).DataTable({
"bInfo" : false,
"pageLength": 20,
"searching": false,
"bPaginate": false,
"columns": [
{
data: 'data',
name: 'data',
"render": function (data, type, row, meta) {
return JSON.stringify(data);
},
defaultContent: ""
},
{
data: 'data.custom_region_info.features.0.geometry.coordinates',
name: 'coordinates',
"render": function (data, type, row, meta) {
console.log("데이타 : ");
console.log(data);
// var coordinates = data.map(function(item) {
// return item["features"][0]["geometry"]["coordinates"];
// });
return JSON.stringify(data);
},
defaultContent: ""
},
{
data: 'temporary',
name: 'temporary',
defaultContent: ""
},
]
});
}
// make a request to Couchbase to get the features in the current extent
var resp_example = [{
"id": "93cabfb5-1da1-49e7-80d1-d336b5e060a8",
"data": {
"custom_region_info": {
"type": "FeatureCollection",
"features": [
{
"geometry": {
"coordinates": [
127.339084,
36.780266
],
"type": "Point"
},
"type": "Feature",
"properties": {
"name": "matzip00",
"shapeContinent": "AS",
"detail": "맛집아입니까",
"shapeCountry": "KR"
}
}
]
},
"custom_region_detail": "맛집아입니까"
},
"temporary": false,
"is_aoi": "true"
}];
function requestUpdatedCadastre(bounds) {
/*$.ajax({
type: 'GET',
url: ATLAS_ADMIN_HOST + "/admin_api/regions/aois",
dataType: 'json',
success: function (result) {
var custom_region_info = result.map(function (item) { return item["data"]["custom_region_info"]}); // 마커와 폴리곤 배열
parseResponseCadastre(custom_region_info);
},
error: function (req, status, error) {
alert('Unable to get cadastral data:' + error);
}
});*/
var custom_region_info = resp_example.map(function (item) { return item["data"]["custom_region_info"]}); // 마커와 폴리곤 배열
parseResponseCadastre(custom_region_info);
}
// parse the features retrieved from Couchbase
function parseResponseCadastre(data) {
if (drawnItems != undefined)
{
map.removeLayer(drawnItems);
}
for(var i=0; i< data.length; i++) {
L.geoJSON(data[i], {
onEachFeature: function (feature, layer) {
layer.bindPopup('<h1> 지역 '+JSON.stringify(feature.properties.name) +'</h1><p> 상세 정보'+ JSON.stringify(feature.properties) +'</p>');
}
}).addTo(map);
}
}
var latLngs; /* 전체 위경도 배열 */
var aoiDetail;
var map = L.map('map');
var drawnItems = new L.FeatureGroup();
map.addLayer(drawnItems);
map.on('load', function(e) {
requestUpdatedCadastre(e.target.getBounds());
});
map.setView([37.507805, 127.056605], 13);
L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token=pk.eyJ1IjoibWFwYm94IiwiYSI6ImNpejY4NXVycTA2emYycXBndHRqcmZ3N3gifQ.rJcFIG214AriISLbB6B5aw', {
maxZoom: 18,
attribution: 'ohoroyoi',
id: 'mapbox.streets'
}).addTo(map);
// var drawnItems = new L.FeatureGroup();
// map.addLayer(drawnItems);
var drawControl = new L.Control.Draw({
draw : {
position : 'topleft',
polygon : true,
polyline : false,
rectangle : false,
circle : false,
circlemarker : false
},
edit: {
featureGroup: drawnItems,
edit: false,
remove: false
}
});
map.addControl(drawControl);
map.on(L.Draw.Event.CREATED, function (e) { /* event create*/
var layer = e.layer;
drawnItems.addLayer(layer);
});
var idIW = L.popup();
function saveIdIW() {
// var parentValue = $('#shapeCountry').val() ? $('#shapeCountry').val() : $('#shapeContinent').val();
// var parentType = $('#parentType').val();
var shapeContinent = $('#shapeContinent').val();
var shapeCountry = $('#shapeCountry').val();
var shapeName = $('#shapeName').val();
var shapeDesc = $('#shapeDesc').val();
var drawings = drawnItems.getLayers(); // drawnItems is a container for the drawn objects
drawings[drawings.length - 1].title = shapeName;
drawings[drawings.length - 1].content = shapeDesc;
drawings[drawings.length - 1].shapeContinent = shapeContinent;
drawings[drawings.length - 1].shapeCountry = shapeCountry;
aoiDetail = {"name" : drawings[0].title, "detail": drawings[0].content, "shapeContinent": drawings[0].shapeContinent, "shapeCountry": drawings[0].shapeCountry};
if (idIW) {
map.closePopup();
}
// $('#clicked_region').clear();
$('#clicked_region').append("<div>" + JSON.stringify(drawnItems.toGeoJSON()) + "</div>");
$('#clicked_region').append("<div>" + JSON.stringify(aoiDetail) + "</div>");
}
map.on('draw:created', function (e) {
var type = e.layerType,
layer = e.layer;
if (type === 'marker') {
// Do marker specific actions
}
if (Array.isArray(layer._latlngs)) {
latLngs = layer._latlngs[0];
} else {
var temp_arr = [];
temp_arr.push(layer._latlng);
latLngs = temp_arr;
}
// Do whatever else you need to. (save to db; add to map etc)
// var idIW = L.popup();
var result = confirm("만들려는 지역이 도시 레벨입니까? \n\n ex) \n 확인 : 홍대 - 도시레벨 \n 취소 : 동유럽 - 국가레벨 이상");
var content = result ?
'<span><b>Shape Continent</b></span><br/>' +
'<input id="shapeContinent" type="text" placeholder="지역을 포함시킬 대륙을 영어로 작성하세요"/>' +
'<br/>' +
'<br/>' +
'<span><b>Shape Country<b/></span><br/>' +
'<input id="shapeCountry" type="text"/>' +
'<br/>' +
'<br/>' +
'<span><b>Shape Name</b></span><br/>' +
'<input id="shapeName" type="text" placeholder="영어로 작성하세요"/>' +
'<br/>' +
'<br/>' +
'<span><b>Shape Description<b/></span>' +
'<br/>' +
'<textarea id="shapeDesc" cols="25" rows="5" placeholder="한글작성 가능"></textarea>' +
'<br/>' +
'<br/>' +
'<input type="button" id="okBtn" value="Save" onclick="saveIdIW()"/>'
:
'<span><b>Shape Continent<b/></span><br/>' +
'<input id="shapeContinent" type="text" placeholder="지역을 포함시킬 대륙을 영어로 작성하세요" />' +
'<br/>' +
'<br/>' +
'<span><b>Shape Name</b></span><br/>' +
'<input id="shapeName" type="text"/>' +
'<br/>' +
'<br/>' +
'<span><b>Shape Description<b/></span>' +
'<br/>' +
'<textarea id="shapeDesc" cols="25" rows="5"></textarea>' +
'<br/>' +
'<br/>' +
'<input type="button" id="okBtn" value="Save" onclick="saveIdIW()"/>';
idIW.setContent(content);
if (layer._bounds) {
var bounds = layer.getBounds();
// idIW.setLataLng($scope.latLng);
idIW.setLatLng(bounds.getCenter()); //calculated based on the e.layertype
} else {
idIW.setLatLng(layer._latlng);
}
idIW.openOn(map);
map.addLayer(layer);
});
map.on('draw:edited', function (e) {
var layers = e.layers;
layers.eachLayer(function (layer) {
//do whatever you want; most likely save back to db
});
});
map.on('draw:deleted', function (e) {
var type = e.layerType,
layer = e.layer;
drawnItems.clearLayers(e.layer);
});
document.getElementById('export').onclick = function(e) {
// Extract GeoJson from featureGroup
var data = drawnItems.toGeoJSON();
data.features[0].properties = aoiDetail;
var convertedData = 'text/json;charset=utf-8,' + encodeURIComponent(JSON.stringify(data));
document.getElementById('export').setAttribute('href', 'data:' + convertedData);
document.getElementById('export').setAttribute('download','data.geojson');
}
document.getElementById('apicall').onclick = function(e) {
var data = drawnItems.toGeoJSON();
data.features[0].properties = aoiDetail;
var polygon = data.features[0].geometry.coordinates;
var postValue = {};
postValue.detail = aoiDetail.detail;
postValue.detailData = data;
postValue.name = aoiDetail.name;
postValue.polygon = polygon;
postValue.shapeContinent = aoiDetail.shapeContinent;
postValue.shapeCountry = aoiDetail.shapeCountry;
$.ajax({
type: "POST",
url: ATLAS_ADMIN_HOST + "/admin_api/regions/add",
data: JSON.stringify(postValue), //aoiDetail
// dataType: "json",
contentType: "application/json;charset=utf-8",
success: function(resp) {
console.log(resp);
alert("추가");
window.location.reload();
},
error: function(error) {
console.log(error);
}
});
}
function getAllAoi() {
$.ajax({
type: "GET",
url: ATLAS_ADMIN_HOST + "/admin_api/regions/aois",
success: function(resp) {
console.log(resp);
},
error: function(error) {
console.log(error);
}
});
}
$(function() {
getAllAoi();
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment