Cemetery Mapping search with Leaflet - codeigniter
How can I do when I retrieve a person from the BD and create a link to direct to the grave on the map?
I do a search in the BD and when I find a person, I want to create a url that, when clicked, shows the map of the cemetery showing the location of the grave.
Here's the code I have so far. It shows me the map, but it doesn't show the grave marker.
<script >
$(document).ready(function(){
var prev_path = prev_marker = null;
$('.btn_search').on('click',function(){
var firstname = $('input[name="deceased_firstname"]').val();
var lastname = $('input[name="deceased_lastname"]').val();
/* var f_firstname = firstname.replace(/ /g, '%20');
var l_lastname = lastname.replace(/ /g, '%20');
*/
var url = '<?=base_url()?>/pages/search_burial/'+firstname+'/'+lastname;
console.log(url);
$.getJSON(url, function(data){
if (data == null) { alert("no results found!"); }
console.log(data);
var icon_grave = L.icon({
iconUrl: "<?=base_url()?>" +'user_template/icons/catholicgrave.png',
iconSize: [30,30] });
var latlngs = []
if(data != null || data != undefined) {
var route = JSON.parse(data.lot_coordinates);
for (var i = 0, len = route.length; i < len; i++) {
latlngs.push(new L.LatLng(route[i][0], route[i][1]));
}
} else {
latlngs = [];
}
var path = L.polyline(latlngs);
var marker = L.marker(latlngs[len - 1]).addTo(map).bindPopup("</br>"+"<strong>Fullname:</strong>"+" "+data.occupant_firstname+" "+data.occupant_middlename+" "+ data.occupant_lastname +"</br>" +
"<strong>Date of Birth:</strong>"+" " +data.occupant_dateofbirth + "</br>"+
"<strong>Date of Death:</strong>"+" " +data.occupant_dateofdeath + "</br>"+
"<strong>Garden:</strong>"+" " +data.garden_name + "</br>"+
"<strong>Block:</strong>"+" " +data.block_name + "</br>"+
"<strong>Lot:</strong>"+" " +data.lot_name + "</br>"+
"<strong>Longitude:</strong>"+" "+data.lot_long + "</br>"+
"<strong>Latitude:</strong>"+" "+data.lot_lat ).openPopup();
if (prev_path != null){
map.removeLayer(prev_path);
}
if(prev_marker != null){
map.removeLayer(prev_marker);
}
prev_path = path;
prev_marker = marker;
//map.removeLayer(path)
//map.addLayer(L.marker(latlngs[0]));
if(latlngs.length > 0) {
map.addLayer(marker);
}
map.addLayer(path);
setTimeout(function(){ path.snakeIn(); }, 3000);
//path.snakeIn();
});
});
});
</script>
<script>
// Creating a map object
var map = L.map('map').setView([-1.055588,2.109375],1);
var base_url = "<?=base_url()?>";
// Creating a Layer object
L.tileLayer('<?php echo base_url("user_template/map/{z}/{x}/{y}.png"); ?>',
{
minZoom: 2,
maxZoom: 4,
continousWorld: false,
noWrap: true,
}).addTo(map);
var bounds = new L.LatLngBounds(new L.LatLng(-70.020587,-132.242584), new L.LatLng(69.900118,140.680943));
map.fitBounds(bounds);
//add standard controls
L.control.coordinates().addTo(map);
//add configured controls
L.control.coordinates({
position:"bottomleft",
decimals:6,
decimalSeperator:".",
labelTemplateLat:"Latitude: {y}",
labelTemplateLng:"Longitude: {x}"
}).addTo(map); //mao ni siya bert naa diay sa taas ang code adto
/*Legend specific*/
var legend = L.control({ position: "bottomright" });
legend.onAdd = function(map) {
var div = L.DomUtil.create("div", "legend");
div.innerHTML += "<h5>Legend:</h5>";
div.innerHTML += '<i style="background: #e8851e"></i><span>Garden</span><br>';
div.innerHTML += '<i style="background: #448D40"></i><span>Block</span><br>';
div.innerHTML += '<i style="background: #ff0000"></i><span>Lot</span><br>';
return div;
};
legend.addTo(map);
var marker_1 = L.marker([-60.064840460104506,13.005095612485837]).addTo(map).bindPopup("Gate is here").openPopup();
map.addLayer(marker_1);
$.getJSON(base_url+"pages/map_gardens", function(data)
{
$.each(data, function(i, field)
{
var mapgarden_longitude_1 = parseFloat(data[0].garden_longitude1);
var mapgarden_latitude_1 = parseFloat(data[0].garden_latitude1);
var mapgarden_longitude_2 = parseFloat(data[0].garden_longitude2);
var mapgarden_latitude_2 = parseFloat(data[0].garden_latitude2);
var mapgarden_longitude_3 = parseFloat(data[0].garden_longitude3);
var mapgarden_latitude_3 = parseFloat(data[0].garden_latitude3);
var mapgarden_longitude_4 = parseFloat(data[0].garden_longitude4);
var mapgarden_latitude_4 = parseFloat(data[0].garden_latitude4);
var polylinePoints = [
[mapgarden_longitude_1, mapgarden_latitude_1],
[mapgarden_longitude_2, mapgarden_latitude_2],
[mapgarden_longitude_3, mapgarden_latitude_3],
[mapgarden_longitude_4, mapgarden_latitude_4],
[mapgarden_longitude_1, mapgarden_latitude_1]];
var polyline = L.polyline(polylinePoints).addTo(map);
});
});
$.getJSON(base_url+"pages/map_gardens", function(data)
{
$.each(data, function(i, field)
{
var mapgarden_longitude_1 = parseFloat(data[i].garden_long1);
var mapgarden_latitude_1 = parseFloat(data[i].garden_lat1);
var mapgarden_longitude_2 = parseFloat(data[i].garden_long2);
var mapgarden_latitude_2 = parseFloat(data[i].garden_lat2);
var mapgarden_longitude_3 = parseFloat(data[i].garden_long3);
var mapgarden_latitude_3 = parseFloat(data[i].garden_lat3);
var mapgarden_longitude_4 = parseFloat(data[i].garden_long4);
var mapgarden_latitude_4 = parseFloat(data[i].garden_lat4);
var mapgarden_longitude_5 = parseFloat(data[i].garden_long5);
var mapgarden_latitude_5 = parseFloat(data[i].garden_lat5);
var mapgarden_longitude_6 = parseFloat(data[i].garden_long6);
var mapgarden_latitude_6 = parseFloat(data[i].garden_lat6);
var mapgarden_longitude_7 = parseFloat(data[i].garden_long7);
var mapgarden_latitude_7 = parseFloat(data[i].garden_lat7);
var mapgarden_longitude_8 = parseFloat(data[i].garden_long8);
var mapgarden_latitude_8 = parseFloat(data[i].garden_lat8);
var mapgarden_longitude_9 = parseFloat(data[i].garden_long9);
var mapgarden_latitude_9 = parseFloat(data[i].garden_lat9);
var mapgarden_longitude_10 = parseFloat(data[i].garden_long10);
var mapgarden_latitude_10 = parseFloat(data[i].garden_lat10);
var mapgarden_longitude_11 = parseFloat(data[i].garden_long11);
var mapgarden_latitude_11 = parseFloat(data[i].garden_lat11);
var mapgarden_longitude_12 = parseFloat(data[i].garden_long12);
var mapgarden_latitude_12 = parseFloat(data[i].garden_lat12);
var mapgarden_longitude_13 = parseFloat(data[i].garden_long13);
var mapgarden_latitude_13 = parseFloat(data[i].garden_lat13);
var mapgarden_longitude_14 = parseFloat(data[i].garden_long14);
var mapgarden_latitude_14 = parseFloat(data[i].garden_lat14);
var mapgarden_longitude_15 = parseFloat(data[i].garden_long15);
var mapgarden_latitude_15 = parseFloat(data[i].garden_lat15);
var mapgarden_longitude_16 = parseFloat(data[i].garden_long16);
var mapgarden_latitude_16 = parseFloat(data[i].garden_lat16);
var polylinePoints_1 = [
[mapgarden_longitude_1, mapgarden_latitude_1],
[mapgarden_longitude_2, mapgarden_latitude_2],
[mapgarden_longitude_3, mapgarden_latitude_3],
[mapgarden_longitude_4, mapgarden_latitude_4],
[mapgarden_longitude_5, mapgarden_latitude_5],
[mapgarden_longitude_6, mapgarden_latitude_6],
[mapgarden_longitude_7, mapgarden_latitude_7],
[mapgarden_longitude_8, mapgarden_latitude_8],
[mapgarden_longitude_9, mapgarden_latitude_9],
[mapgarden_longitude_10, mapgarden_latitude_10],
[mapgarden_longitude_11, mapgarden_latitude_11],
[mapgarden_longitude_12, mapgarden_latitude_12],
[mapgarden_longitude_13, mapgarden_latitude_13],
[mapgarden_longitude_14, mapgarden_latitude_14],
[mapgarden_longitude_15, mapgarden_latitude_15],
[mapgarden_longitude_16, mapgarden_latitude_16],
[mapgarden_longitude_1, mapgarden_latitude_1]];
var polyline = L.polyline(polylinePoints_1, {
color: "#e8851e",
}).addTo(map);
});
});
$.getJSON(base_url+"pages/map_blocks", function(data)
{
$.each(data, function(i, field)
{
var mapblocks_longitude_1 = parseFloat(data[i].block_long1);
var mapblocks_latitude_1 = parseFloat(data[i].block_lat1);
var mapblocks_longitude_2 = parseFloat(data[i].block_long2);
var mapblocks_latitude_2 = parseFloat(data[i].block_lat2);
var mapblocks_longitude_3 = parseFloat(data[i].block_long3);
var mapblocks_latitude_3 = parseFloat(data[i].block_lat3);
var mapblocks_longitude_4 = parseFloat(data[i].block_long4);
var mapblocks_latitude_4 = parseFloat(data[i].block_lat4);
var polygonPoints = [
[mapblocks_longitude_1, mapblocks_latitude_1],
[mapblocks_longitude_2, mapblocks_latitude_2],
[mapblocks_longitude_3, mapblocks_latitude_3],
[mapblocks_longitude_4, mapblocks_latitude_4]];
var poly = L.polygon([polygonPoints],{
color: "green"
}).addTo(map);
});
});
$.getJSON(base_url+"pages/map_lots", function(data)
{
$.each(data, function(i, field)
{
var mapLots_longitude = parseFloat(data[i].lot_long);
var mapLots_latitude = parseFloat(data[i].lot_lat);
var circle = L.circle([mapLots_longitude, mapLots_latitude], {
color: "red",
fillColor: "#f03",
fillOpacity: 1.5,
radius: 50.0
}).addTo(map);
});
});
</script>
Related
Google Maps: add listener to dynamically created marker outside initialize function
I have been trying for days to add an event listener for an infoWindow to markers that are created on Ajax success. The mouseover event is never fired, so there must be something I'm doing wrong in adding the listener. The listener that does NOT work is for the marker restMarker. The dragend listener for addressMarker in the initialize() function works fine. I have tried adding the listener in multiple ways: google.maps.event.addListener(markerObject,'mouseover',function(){}) and markerObject.addListener('mouseover',function(){}). I have tried giving the restMarker global scope. I have read the following: Dynamically Adding Listeners To Google Maps Markers create event listener to dynamically created google-map marker ...and more. I have infoWindows working fine with dynamically created markers in other projects. The only difference I'm aware of in the working projects is that the markers are created in the map initialize() function instead of in an ajax success function. Am I doing anything obviously wrong? <script type='text/javascript'> var zoneMap; var currentRestMarkers = []; var markerInfoWindow; var distances = [{"fee":2,"distance":5,"available":1},{"fee":3,"distance":7,"available":1},{"available":1,"distance":9,"fee":7},{"fee":9,"available":0,"distance":10}]; var ajaxResponse = {"success":[{"duration":"11.5","name":"Backyard Bistro","lng":-78.7253,"lat":35.7989,"distance":6.64,"restId":"179"},{"lat":35.7796,"lng":-78.6758,"restId":"180","distance":7.5,"name":"Baja Burrito","duration":"13.3"},{"name":"Mi Rancho","duration":"15.6","lng":-78.6482,"lat":35.7491,"restId":"183","distance":6.32},{"lat":35.7757,"lng":-78.6363,"distance":4.67,"restId":"188","name":"El Rodeo Downtown","duration":"13.7"},{"duration":"9.2","name":"El Rodeo North","lng":-78.6262,"lat":35.8137,"distance":3.35,"restId":"189"},{"name":"Fallon's Flowers","duration":"9.1","restId":"192","distance":2.92,"lat":35.789,"lng":-78.6507},{"lng":-78.6397,"lat":35.7742,"restId":"193","distance":4.62,"name":"Fire Wok","duration":"14.1"},{"lng":-78.6131,"lat":35.8051,"restId":"194","distance":6.21,"name":"Gateway","duration":"9.8"},{"restId":"195","distance":27.99,"lng":-79.0564,"lat":35.9152,"name":"Gift Cards ","duration":"35.6"},{"name":"Jumbo China","duration":"8.5","lng":-78.6262,"lat":35.819,"distance":2.87,"restId":"197"},{"lng":-78.6456,"lat":35.8817,"restId":"198","distance":4.93,"name":"La Rancherita","duration":"12.0"},{"duration":"8.9","name":"Mami Nora's","restId":"205","distance":3.35,"lat":35.8137,"lng":-78.6271},{"distance":2.94,"restId":"209","lat":35.7883,"lng":-78.6474,"duration":"8.0","name":"Mellow Mushroom"},{"distance":7.88,"restId":"212","lng":-78.7387,"lat":35.7878,"duration":"12.3","name":"Ole Time BBQ"},{"lng":-78.6388,"lat":35.8374,"restId":"214","distance":2.23,"duration":"7.0","name":"Piola"},{"name":"The Remedy Diner 2.0 - Brunch","duration":"11.9","lng":-78.656,"lat":35.7824,"distance":4.24,"restId":"216"},{"lng":-78.656,"lat":35.7824,"restId":"217","distance":4.24,"duration":"11.9","name":"The Remedy Diner 2.0"},{"distance":7.66,"restId":"218","lng":-78.6773,"lat":35.7777,"name":"Sammy's Tap & Grill","duration":"13.4"},{"lng":-78.621,"lat":35.8238,"distance":4.39,"restId":"219","duration":"8.4","name":"Shaba Shabu"},{"name":"Spring Rolls","duration":"5.9","distance":1.88,"restId":"220","lng":-78.6409,"lat":35.8399},{"duration":"9.6","name":"Thaiphoon","restId":"222","distance":3.2,"lat":35.7845,"lng":-78.6477},{"lat":35.7776,"lng":-78.6398,"restId":"223","distance":4.3,"duration":"11.6","name":"The Big Easy"},{"lng":-78.6433,"lat":35.8364,"restId":"225","distance":1.68,"duration":"5.5","name":"The Q Shack"},{"duration":"14.4","name":"Vic's Italian","lng":-78.6356,"lat":35.7759,"restId":"226","distance":4.72},{"restId":"227","distance":1.68,"lng":-78.6433,"lat":35.8364,"name":"Which Wich North Hills","duration":"5.5"},{"lat":35.7912,"lng":-78.6799,"restId":"245","distance":5.89,"duration":"10.5","name":"The Wild Cook's Indian Grill"},{"lng":-78.6237,"lat":35.873,"restId":"301","distance":4.68,"name":"Taj Mahal North","duration":"12.9"},{"restId":"820","distance":6.29,"lng":-78.6825,"lat":35.8986,"duration":"14.5","name":"El Dorado "},{"name":"Taza Grill","duration":"12.8","restId":"821","distance":4.84,"lat":35.8693,"lng":-78.6211},{"duration":"14.9","name":"Sassool","restId":"824","distance":6.83,"lat":35.9043,"lng":-78.6567},{"lng":-78.5797,"lat":35.8477,"distance":8.45,"restId":"830","name":"Alpaca Peruvian Charcoal Chicken","duration":"13.9"},{"distance":6.21,"restId":"831","lat":35.899,"lng":-78.653,"name":"Shish Kabob Six Forks","duration":"14.1"},{"distance":2.87,"restId":"923","lng":-78.6262,"lat":35.819,"name":"Tropical Picken Chicken","duration":"8.5"},{"duration":"10.3","name":"Wicked Taco","lat":35.7852,"lng":-78.6923,"restId":"931","distance":6.48},{"duration":"14.8","name":"Despina's Cafe","restId":"1142","distance":6.31,"lng":-78.6824,"lat":35.9015},{"duration":"4.7","name":"WhichWich Crabtree","lat":35.8391,"lng":-78.6752,"distance":1.7,"restId":"1242"},{"duration":"6.3","name":"Pharaoh's Grill at North Hills","distance":1.86,"restId":"1296","lng":-78.6434,"lat":35.8403},{"name":"Pharaoh's at the Museum","duration":"12.2","restId":"1297","distance":4.43,"lat":35.7818,"lng":-78.6386},{"restId":"1298","distance":2.54,"lng":-78.6298,"lat":35.8215,"name":"Gorilla Grill","duration":"6.5"},{"name":"My Way Tavern","duration":"9.8","lng":-78.6506,"lat":35.7872,"restId":"1307","distance":3.04}]}; function initialize() { var myLatlng = new google.maps.LatLng(35.8013,-78.6409); var geocoder = new google.maps.Geocoder(); var mapOptions = { zoom: 13, center: myLatlng, panControl: false, zoomControl: true, mapTypeControl: false, scaleControl: true, streetViewControl: false, overviewMapControl: false, mapTypeId: google.maps.MapTypeId.ROADMAP }; zoneMap = new google.maps.Map(document.getElementById('map_canvas'), mapOptions); var addressMarker = new google.maps.Marker({ position: zoneMap.center, map: zoneMap, clickable: true, draggable: true, flat: true, icon: 'https://maps.google.com/mapfiles/ms/icons/blue-dot.png' }); google.maps.event.addListener(addressMarker, 'dragend', function(event) { var markerNewLatLng=event.latLng; geocoder.geocode({'latLng': markerNewLatLng}, function(results, status) { if (status == google.maps.GeocoderStatus.OK) { showAvailableRests(markerNewLatLng.lat(),markerNewLatLng.lng()); } else { console.log('Geocoder failed due to: ' + status); } }); }); } function loadScript() { var acScript = document.createElement('script'); acScript.type = 'text/javascript'; acScript.src = 'https://maps.googleapis.com/maps/api/js?libraries=places&callback=initialize'; document.body.appendChild(acScript); } function showAvailableRests(whichLat,whichLng) { var rest_list = jQuery('#rest_list'); jQuery(rest_list).empty(); jQuery('#restCount').html(''); if (currentRestMarkers.length > 0) { for (var i in currentRestMarkers) { currentRestMarkers[i].setMap(null); } currentRestMarkers = []; } var restCount = 0; for (var i=0; i < ajaxResponse.success.length; i++ ) { var iconColor = 'green.png'; var available = 1; var tierClass = 'tier1'; for (var j=0; j < distances.length; j++ ) { if (ajaxResponse.success[i].distance >= distances[j].distance) { if (distances[j].available == 0) { available = 0; } if (j === 0) { iconColor = 'yellow.png'; tierClass = 'tier2'; } else if (j === 1) { iconColor = 'orange.png'; tierClass = 'tier3'; } else if (j > 1) { iconColor = 'purple.png'; tierClass = 'tier4'; } } else { break; // if it is not greater than the shorter distance, it is not greater than longer ones either } } if (available === 0) { // if this restaurant is not available at this distance //continue; // skip the rest for unavailable iconColor = 'red.png'; tierClass = 'unavailable'; } else { restCount++; } var restDiv = jQuery(document.createElement('div')); var distanceTier = jQuery(document.createElement('span')).html(' ').addClass('distance-tier ' + tierClass).appendTo(restDiv); var restDist = jQuery(document.createElement('span')).html(ajaxResponse.success[i].distance + ' mi.').addClass('rest-distance').appendTo(restDiv); var restName = jQuery(document.createElement('span')).html(ajaxResponse.success[i].name).addClass('rest-name').appendTo(restDiv); jQuery(restDiv).appendTo(rest_list); var restMarkerPosition = new google.maps.LatLng(ajaxResponse.success[i].lat,ajaxResponse.success[i].lng); var restMarker = new google.maps.Marker({ position: restMarkerPosition, map: zoneMap, clickable: false, draggable: false, flat: true, icon: 'https://maps.google.com/mapfiles/ms/icons/' + iconColor }); currentRestMarkers.push(restMarker); google.maps.event.addListener(restMarker, 'mouseover', function(e) { console.log('mouseover event fired'); // the mouseover event is never fired!!! showRestWindow(e, ajaxResponse.success[i].name, ajaxResponse.success[i].distance); }); /*restMarker.addListener('mouseover', function() { new google.maps.InfoWindow({ content: "<div><strong>" + ajaxResponse.success[i].name + "<\/strong><br>" + ajaxResponse.success[i].distance + " miles<\/div>", disableAutoPan: true, }); markerInfoWindow.open(zoneMap, this); });*/ jQuery('#restCount').html(restCount); } } function showRestWindow(event, name, distance) { markerInfoWindow = new google.maps.InfoWindow({ content: "<div><strong>" + name + "<\/strong><br>" + distance + " miles<\/div>", disableAutoPan: true, position: event.latLng, }); markerInfoWindow.open(zoneMap); }; jQuery(document).ready(function () { loadScript(); return false; }); </script> <div id='map_container'> <div id='map_canvas'></div> </div> <div id='column_right'> <p><b>Available Restaurants: <span id='restCount'></span></b></p> <div id='rest_list'></div> </div>
Ckeditor scrollbar marker / Text Position Indicator
I would like to implement scrollbar marker into ckeditor and i can't seem to find the right way to do it i have triyed this code var win = new CKEDITOR.dom.window( window ); var pos = win.getScrollPosition(); console.log(pos); but it only return the google chrome scrollbar x=0 & Y=0 var win = new CKEDITOR.dom.window( domWindow ); var pos = win.getScrollPosition(); console.log(pos); and this give me an error domWindow is not defined i found this example it may help: https://codepen.io/Rplus/pen/mEjWJm (() => { var containerQS = '.article'; var container = document.querySelector(containerQS); var form = document.querySelector('.form'); var input = form.querySelector('input[type="text"]'); var markClass = 'mark'; var markerHeight = '2px'; var _color = 'currentColor'; var containerY = container.offsetTop; var containerH = container.scrollHeight; var customStyle = document.createElement('style'); container.appendChild(customStyle); var renderScrollMarker = ($parent, posArr) => { var _posArr = posArr.map(i => { return `transparent ${i}, ${_color} ${i}, ${_color} calc(${i} + ${markerHeight}), transparent calc(${i} + ${markerHeight})`; }); customStyle.innerHTML = `article::-webkit-scrollbar-track { background-image: linear-gradient(${_posArr.join()}); }`; }; var calcEleRelativePos = ($ele) => { return ($ele.offsetTop - containerY) / containerH; }; var markOpt = { className: markClass, done: function () { var marks = document.querySelectorAll(`.${markClass}`); var allY = [].map.call(marks, (mark) => { return (calcEleRelativePos(mark) * 100).toFixed(2) + '%'; }); renderScrollMarker(container, allY); console.log(allY); } }; var instance = new Mark(container); form.addEventListener('submit', (e) => { e.preventDefault(); var _text = input.value.trim(); console.log(_text, form.oldText); if (_text === '') { instance.unmark(markOpt); return; } form.oldText = _text; instance.unmark().mark(_text, markOpt); }); // trigger form.querySelector('input[type="submit"]').click(); })(); but as ckeditor secures a lot of element, i would love to know if any one has done this before with CKeditor
i just got the real editor scrollbar position, i only need to put a marker using style or any availble methode var win=CKEDITOR.instances.editor1.document.getWindow(); var pos = win.getScrollPosition().y; console.log(pos);
this worked for me : var jqDocument = $(editor.document.$); var documentHeight = jqDocument.height(); var scrollTo =jqDocument.scrollTop(); var docHeight = jqDocument.height(); var scrollPercent = (scroll)/(docHeight); var scrollPercentRounded = Math.round(scrollPercent*100); $(".ui-slider-handle").css("bottom", 100-scrollPercentRounded+"%");
OpenLayers3 : Draggable OverviewMapControl
In OpenLayers 2, in the OverviewMapControl, you can drag the "box" to move the map. You can not do this in OpenLayers 3. I've tried to implement a custom control based on https://github.com/openlayers/ol3/blob/master/src/ol/control/overviewmapcontrol.js, but you can not use goog.xxx or other fancy stuff like ol.extent.scaleFromCenter when you are not in debug ! How should I proceed ? basically, implementing drag'n drop is fairly "simple" : var dragging = null; var getMap = this.getMap.bind(this); //during ctor of a control, we have no access to the map ! $(document.body).on("mousemove", function (e) { if (dragging) { dragging.el.offset({ top: e.pageY, left: e.pageX }); } }); $(box).on("mousedown", function (e) { dragging = { el: $(e.target) }; }); $(document.body).on("mouseup", function (e) { if (dragging) { debugger; var coords = ovmap.getEventCoordinate(e.originalEvent); //TODO: taking event coordinates is not good, we must use center of the box coordinates //the problem is that ovmap.getCoordinateFromPixel(dragging.el.offset()) is not working at all because we need to adjust ovmap viewport getMap().getView().setCenter(coords); dragging = null; } });
For those interested (which does not seem to be the case at the moment :)), here is the way I solved /** * Mostly a big copy/paste from https://raw.githubusercontent.com/openlayers/ol3/master/src/ol/control/overviewmapcontrol.js * without rotation and zoom/dezoom plus some adapations from http://ol3.qtibia.ro/build/examples/overviewmap-custom-drag.html * to add the possibility to drag the box on the minimap to move the main map */ ol.control.CustomOverviewMap = function (opt_options) { var options = typeof opt_options !== 'undefined' ? opt_options : {}; this.collapsed_ = typeof options.collapsed !== 'undefined' ? options.collapsed : true; this.onCollapseOrExpand = options.onCollapseOrExpand || function () { }; this.needFirstRenderUpdate_ = this.collapsed_; //prepare the hack to render the map when uncollapsed the first time var tipLabel = typeof options.tipLabel !== 'undefined' ? options.tipLabel : 'Overview map'; this.collapseLabel_ = $('<span>\u00BB</span>').get(0); this.label_ = $('<span>\u00AB</span>').get(0); var activeLabel = (!this.collapsed_) ? this.collapseLabel_ : this.label_; var button = $('<button type="button" title="{0}"></button>'.replace('{0}', tipLabel)).append(activeLabel); button.on('click', this.handleClick_.bind(this)); //ol.control.Control.bindMouseOutFocusOutBlur(button); button.on('mouseout', function () { this.blur(); }); button.on('focusout', function () { this.blur(); }); var ovmapDiv = $('<div class="ol-overviewmap-map"></div>').get(0); this.ovmap_ = new ol.Map({ controls: new ol.Collection(), interactions: new ol.Collection(), layers: [options.tileLayer], target: ovmapDiv, view: new ol.View(opt_options.view) }); var box = $('<div class="ol-overviewmap-box"></div>'); this.boxOverlay_ = new ol.Overlay({ position: [0, 0], positioning: 'bottom-left', element: box.get(0) }); this.ovmap_.addOverlay(this.boxOverlay_); var cssClasses = 'ol-overviewmap ol-unselectable ol-control' + (this.collapsed_ ? ' ol-collapsed' : ''); var element = $('<div class="{0}"></div>'.replace('{0}', cssClasses)).append(ovmapDiv).append(button).get(0); ol.control.Control.call(this, { element: element, render: ol.control.CustomOverviewMap.render }); // deal with dragable minimap this.dragging = null; box.on("mousedown", this.onStartDrag.bind(this)); $(document.body).on("mousemove", this.onDrag.bind(this)); $(document.body).on("mouseup", this.onEndDrag.bind(this)); }; ol.inherits(ol.control.CustomOverviewMap, ol.control.Control); ol.control.CustomOverviewMap.prototype.onStartDrag = function (e) { // remember some data to use during onDrag or onDragEnd var box = $(e.target); this.dragging = { el: box, evPos: { top: e.pageY, left: e.pageX }, elPos: box.offset() }; } ol.control.CustomOverviewMap.prototype.onDrag = function (e) { if (this.dragging) { //set the position of the box to be oldPos+translation(ev) var curOffset = this.dragging.el.offset(); var newOffset = { top: curOffset.top + (e.pageY - this.dragging.evPos.top), left: curOffset.left + (e.pageX - this.dragging.evPos.left) }; this.dragging.evPos = { top: e.pageY, left: e.pageX }; this.dragging.el.offset(newOffset); } } ol.control.CustomOverviewMap.prototype.onEndDrag = function (e) { if (this.dragging) { //see ol3.qtibia.ro href at the top of the class to understand this var map = this.getMap(); var offset = this.dragging.el.position(); var divSize = [this.dragging.el.width(), this.dragging.el.height()]; var mapSize = map.getSize(); var c = map.getView().getResolution(); var xMove = offset.left * (Math.abs(mapSize[0] / divSize[0])); var yMove = offset.top * (Math.abs(mapSize[1] / divSize[1])); var bottomLeft = [0 + xMove, mapSize[1] + yMove]; var topRight = [mapSize[0] + xMove, 0 + yMove]; var left = map.getCoordinateFromPixel(bottomLeft); var top = map.getCoordinateFromPixel(topRight); var extent = [left[0], left[1], top[0], top[1]]; map.getView().fitExtent(extent, map.getSize()); map.getView().setResolution(c); //reset the element at the original position so that when the main map will trigger //the moveend event, this event will be replayed on the box of the minimap this.dragging.el.offset(this.dragging.elPos); this.dragging = null; } } ol.control.CustomOverviewMap.render = function (mapEvent) { //see original OverviewMap href at the top of the class to understand this var map = this.getMap(); var ovmap = this.ovmap_; var mapSize = map.getSize(); var view = map.getView(); var ovview = ovmap.getView(); var overlay = this.boxOverlay_; var box = this.boxOverlay_.getElement(); var extent = view.calculateExtent(mapSize); var ovresolution = ovview.getResolution(); var bottomLeft = ol.extent.getBottomLeft(extent); var topRight = ol.extent.getTopRight(extent); overlay.setPosition(bottomLeft); // set box size calculated from map extent size and overview map resolution if (box) { var boxWidth = Math.abs((bottomLeft[0] - topRight[0]) / ovresolution); var boxHeight = Math.abs((topRight[1] - bottomLeft[1]) / ovresolution); $(box).width(boxWidth).height(boxHeight); } }; ol.control.CustomOverviewMap.prototype.handleClick_ = function (event) { event.preventDefault(); this.collapsed_ = !this.collapsed_; $(this.element).toggleClass('ol-collapsed'); // change label if (this.collapsed_) { this.collapseLabel_.parentNode.replaceChild(this.label_, this.collapseLabel_); } else { this.label_.parentNode.replaceChild(this.collapseLabel_, this.label_); } // manage overview map if it had not been rendered before and control is expanded if (!this.collapsed_ && this.needFirstRenderUpdate_) { this.needFirstRenderUpdate_ = false; this.ovmap_.updateSize(); this.ovmap_.once("postrender", function () { this.render(); }.bind(this)); } //trigger event this.onCollapseOrExpand(this.collapsed_); };
Resize image and upload in couchdb or upload url blob to couchdb
I need to upload attached resized images into a couchdb doc. Right now I'm not resizing images, only uploading them by using the following code: function attachFile(event) { event.preventDefault(); var form_data = {}; $("form.attach-file :file").each(function() { form_data[this.name] = this.value; }); if (!form_data._attachments || form_data._attachments.length == 0) { alert("Please select a file to upload."); return; } var id = $("#ant-show").data("doc")._id; $(this).ajaxSubmit({ url: "db/" + $.couch.encodeDocId(id), success: function(resp) { $('#modal-attach').modal("hide"); helios_link(id); } }); } The code I'm using to rezise images, but that doesn't work to upload them, is the following: function attachFile(event) { function isImage (str) { return str.match(/(^data:image\/.*,)|(\.(jp(e|g|eg)|gif|png|bmp|webp|svg)((\?|#).*)?$)/i); } function resizeAndUpload(file, callback, progress) { var reader = new FileReader(); reader.onloadend = function() { var tempImg = new Image(); tempImg.onload = function() { var MAX_WIDTH = 500; var MAX_HEIGHT = 500; var tempW = tempImg.width; var tempH = tempImg.height; if (tempW > tempH) { if (tempW > MAX_WIDTH) { tempH *= MAX_WIDTH / tempW; tempW = MAX_WIDTH; } } else { if (tempH > MAX_HEIGHT) { tempW *= MAX_HEIGHT / tempH; tempH = MAX_HEIGHT; } } var resizedCanvas = document.createElement('canvas'); resizedCanvas.width = tempW; resizedCanvas.height = tempH; var ctx = resizedCanvas.getContext("2d"); ctx.drawImage(this, 0, 0, tempW, tempH); var dataURL = resizedCanvas.toDataURL("image/jpeg"); var file = dataURLtoBlob(dataURL); var fd = $("#upload"); fd.append("_attachments", file); var id = $("#ant-show").data("doc")._id; console.log(fd); fd.ajaxSubmit({ url: "db/" + $.couch.encodeDocId(id), success: function(resp) { $('#modal-attach').modal("hide"); helios_link(id); } }); }; tempImg.src = reader.result; } reader.readAsDataURL(file); } function dataURLtoBlob(dataURL) { // Decodifica dataURL var binary = atob(dataURL.split(',')[1]); // Se transfiere a un array de 8-bit unsigned var array = []; var length = binary.length; for(var i = 0; i < length; i++) { array.push(binary.charCodeAt(i)); } // Retorna el objeto Blob return new Blob([new Uint8Array(array)], {type: 'image/jpeg'}); } function uploaded(response) { // Código siguiente a la subida } function progressBar(percent) { // Código durante la subida } event.preventDefault(); console.clear(); var files = document.getElementById('_attachments').files; console.log(files); resizeAndUpload(files[0], uploaded, progressBar); } Do anybody know how can I improve my code to make it work? I would like to have in fact two different solutions, one that helps me to improve my code and the second one, to get instructions on how to upload a URL BLOB as attachments into a couchdb document.
I am facing difficulty to load multiple marker in google map in my code, in my code only one marker will be loaded in gmap, please give me solution
<script type="text/javascript"> var map; var mc; //marker clusterer var mcOptions = { gridSize: 10, maxZoom: 8 }; var infowindow = new google.maps.InfoWindow(); //global infowindow var geocoder = new google.maps.Geocoder(); //geocoder var address = new Array("15.8700, 74.5000", "15.871463, 74.500777", "15.871505, 74.500884", "32.7714,-97.2915");`enter code here` var content = new Array("Unit`enter code here`No1", "UnitNo42", "UnitNo43", "UnitNo44"); //min and max limits for multiplier, for random numbers //keep the range pretty small, so markers are kept close by var min = .999999; var max = 1.000001; function createMarker(latlng, text) { var marker = new google.maps.Marker({ position: latlng, map: map }); ///get array of markers currently in cluster var allMarkers = mc.getMarkers(); //check to see if any of the existing markers match the latlng of the new marker if (allMarkers.length != 0) { for (i = 0; i < allMarkers.length; i++) { var existingMarker = allMarkers[i]; var pos = existingMarker.getPosition(); if (latlng.equals(pos)) { text = text + " & " + content[i]; } } } // WHERE TO ADD: mc.addMarker(marker); //?? google.maps.event.addListener(marker, 'click', function () { infowindow.close(); infowindow.setContent(text); infowindow.open(map, marker); }); return marker; } function initialize() { var options = { zoom: 2, center: new google.maps.LatLng(21.7679, 78.8718), mapTypeId: google.maps.MapTypeId.ROADMAP }; map = new google.maps.Map(document.getElementById('map'), options); var gmarkers = []; for (i = 0; i < address.length; i++) { var ptStr = address[i]; var coords = ptStr.split(","); var latlng = new google.maps.LatLng(parseFloat(coords[0]), parseFloat(coords[1])) gmarkers.push(createMarker(latlng, content[i])); } //marker cluster mc = new MarkerClusterer(map, gmarkers, mcOptions); for (i = 0; i < address.length; i++) { geocodeAddress(address[i], i); } } </script>
var mapOptions = { center: new google.maps.LatLng(20, 77), zoom: 3, mapTypeId: google.maps.MapTypeId.SATELLITE }; var map = new google.maps.Map(document.getElementById("map_Google"), mapOptions); var allmarkers = new Array(); ; var bounds = new google.maps.LatLngBounds(); var infowindow = new google.maps.InfoWindow(); var marker, i; for (i = 0; i < markers.length; i++) { if (allmarkers.length >= i + 1) { } else { var image = { url: markers[i][3] }; marker = new google.maps.Marker({ position: new google.maps.LatLng(markers[i][1], markers[i][2]), map: map, icon: image, animation: google.maps.Animation.DROP, cursor: "default" }); marker.mycategory = "Halla"; allmarkers.push(marker); bounds.extend(marker.getPosition()); google.maps.event.addListener(allmarkers[i], 'click', (function (allmarkers, i) { return function () { //map.setZoom(21); //map.setCenter(marker.getPosition()); infowindow.setContent(markers[i][0]); infowindow.open(map, allmarkers[i]); } }) (allmarkers, i)); } map.fitBounds(bounds); });