i am trying to show csv data in my map .The map i created from json data . But now it doesn't show any csv data but showing only json data.
tootip.html(" District :"+"\n" +d.id +d.Family_Feud_m)
here d.id 's "id" is from json file and d.Family_Feud_m's "Family_Feud_m" from csv file .
Here is my full js code:
var Districts=[];
var bardata = [];
var width = 500,
height = 700;
var scal = 5000;
var tootip = d3.select('body')
.append('div')
.style('position','absolute')
.style('padding','0 10px')
.style('background','white')
.style('opacity',0)
var projection = d3.geo.mercator()
.scale(scal)
.translate([-76.5/50.0 * scal, scal/2-scal/55]);
var path = d3.geo.path()
.projection(projection);
var svg = d3.select(".viewer")
.append("svg")
.attr("width", width)
.attr("height", height);
function redrawMap()
{
svg.selectAll(".subunit")
.style('fill',function(d){
amount = Districts[d.id];
if(amount == 0 || amount== undefined)
return 'rgba(0,0,0,0.5)';
return 'rgba(43,120,200,'+amount*1.0/10.0+')';
});
}
d3.csv('./data/resultsuicide.csv',function(data){
console.log(data)
for(key in data) {
bardata.push(data[key].value)
}
d3.json("./data/bd.json", function(error, bd) {
svg.selectAll(".subunit")
.data(topojson.feature(bd, bd.objects.subunits).features)
.enter().append("path")
.attr("class", function(d) { return "subunit " + d.id; })
.attr("d", path)
.on('mouseover',function(d){
tootip.transition()
.style('opacity',.9)
tootip.html(" District :"+"\n" +d.id +d.Family_Feud_m)
.style('left',(d3.event.pageX-35)+'px')
.style('top',(d3.event.pageY-30)+'px')
tempcolor = this.style.fill;
d3.select(this)
.style('opacity',.5)
.style('fill','green')
})
.on('mouseout',function(d){
d3.select(this)
.style('opacity',1)
.style('fill',tempcolor)
})
redrawMap();
});
});
//thanks in advance
Related
I am working with ASTER images and I am trying to convert radiance values to reflectance. Currently, I converted DN values to radiance and I don't know what else to do. Also, I found a Landsat function, but I don't know if it works for this case. This is my code:
var AOI = ee.Geometry.Polygon([
[-75.01530862531565,9.762481145514606],[-74.58134866437815,9.762481145514606],
[-74.58134866437815,10.27637106477599],[-75.01530862531565,10.27637106477599]]);
var dataset = ee.ImageCollection('ASTER/AST_L1T_003')
.filter(ee.Filter.date('2000-01-01', '2020-10-30'))
.filterBounds(AOI)
.filterMetadata('CLOUDCOVER', 'less_than', 1)
.filter(ee.Filter.and(
ee.Filter.notNull(['GAIN_COEFFICIENT_B01']),
ee.Filter.notNull(['GAIN_COEFFICIENT_B02']),
ee.Filter.notNull(['GAIN_COEFFICIENT_B3N']),
ee.Filter.notNull(['GAIN_COEFFICIENT_B04']),
ee.Filter.notNull(['GAIN_COEFFICIENT_B05']),
ee.Filter.notNull(['GAIN_COEFFICIENT_B06']),
ee.Filter.notNull(['GAIN_COEFFICIENT_B07']),
ee.Filter.notNull(['GAIN_COEFFICIENT_B08']),
ee.Filter.notNull(['GAIN_COEFFICIENT_B09'])));
print(dataset)
// red and NIR channel digital numbers to at sensor radiance
function bands (img) {
var gainB1 = 0.676;
var gainB2= 0.708;
var gainB3N = 0.862;
var gainB4= 0.2174;
var gainB5 = 0.0696;
var gainB6= 0.0625;
var gainB7 = 0.0597;
var gainB8= 0.0417;
var gainB9 = 0.0318;
var rad_b1 = (img.select('B01').subtract(1)).multiply(gainB1);
var rad_b2 = (img.select('B02').subtract(1)).multiply(gainB2);
var rad_b3 = (img.select('B3N') .subtract(1)).multiply(gainB3N);
var rad_b4 = (img.select('B04').subtract(1)).multiply(gainB4);
var rad_b5 = (img.select('B05') .subtract(1)).multiply(gainB5);
var rad_b6 = (img.select('B06').subtract(1)).multiply(gainB6);
var rad_b7 = (img.select('B07').subtract(1)).multiply(gainB7);
var rad_b8 = (img.select('B08').subtract(1)).multiply(gainB8);
var rad_b9 = (img.select('B09').subtract(1)).multiply(gainB9);
return (rad_b1).addBands(rad_b2).addBands(rad_b3).addBands(rad_b4)
.addBands(rad_b5).addBands(rad_b6).addBands(rad_b7)
.addBands(rad_b8).addBands(rad_b9);
}
// add all selected bands with radiance values
var rad_bands =dataset.map(bands)
print(rad_bands)
function copyProps(index){
var source = ee.Image(dataset.toList(dataset.size()).get(index))
var dest = ee.Image(rad_bands.toList(rad_bands.size()).get(index))
var image = ee.Image(dest.copyProperties(source))
return image
}
var seq = ee.List.sequence(0, rad_bands.size().subtract(1))
print(seq)
var final_col = ee.ImageCollection(seq.map(copyProps))
https://code.earthengine.google.com/5b2dfc9b609ba5738be49ae2915d3980
I used the .combine command to convert two image collections into a two-band image collection (in the last line) to use in a function in the next step. This command is executed but writes 0 elements in the console. Where does this problem come from?
code link: https://code.earthengine.google.com/ed0992093ff830d926c7dd14403477c6
Code:
var ndvi = function(img){
var bands = img.select(['B2','B3','B4','B8']).multiply(0.0001)
.clip(geometry);
var index = bands.normalizedDifference(['B8','B4']).rename('NDVI_S2');
return index
.copyProperties(img,['system:time_start','system:time_end','system:index']);
};
var S2 = ee.ImageCollection('COPERNICUS/S2_SR')
.filterBounds(geometry)
.filterDate('2018-10-24','2019-06-30')
//.filter(ee.Filter.lte('CLOUDY_PIXEL_PERCENTAGE',20))
.map(ndvi);
print(S2);
var START = '2018-10-24';
var END = '2019-06-30';
var DATES = [ '2018-12-19', '2018-12-29', '2019-01-23', '2019-02-12', '2019-03-04',
'2019-03-19', '2019-04-08', '2019-04-13', '2019-05-13', '2019-05-18', '2019-05-23',
'2019-05-28', '2019-06-02', '2019-06-07', '2019-06-12', '2019-06-17', '2019-06-22',
'2019-06-27'];
var addTime = function(x) {
return x.set('Date', ee.Date(x.get('system:time_start')).format("YYYY-MM-dd"))};
var Sentinel = ee.ImageCollection(S2)
.filter(ee.Filter.date(START, END))
.map(addTime)
.filter(ee.Filter.inList('Date',ee.List(DATES)));
print(Sentinel);
var PMODIS =
ee.Image('MODIS/006/MCD43A4/2018_12_19').select('Nadir_Reflectance_Band4');
var MODProjection = PMODIS.projection();
print('MODIS projection:', MODProjection);
var Viz = {min: 0, max: 1, palette: ['be6c44','ca3a3a','e4ae0c','565c04','819536']};
var S2_resampled = Sentinel.map(function(img){
var S2Mean = img
// Force the next reprojection to aggregate instead of resampling.
.reduceResolution({
reducer: ee.Reducer.mean(),
maxPixels: 2146
})
// Request the data at the scale and projection of the Sentinel image.
.reproject({
crs: MODProjection
});
return S2Mean
.copyProperties(img,['system:time_start','system:time_end','system:index']);
});
Map.addLayer(S2_resampled)
var M_ndvi = function(img){
var bands =
img.select(['Nadir_Reflectance_Band1','Nadir_Reflectance_Band5']).multiply(0.0001)
.clip(geometry);
var index=bands
.normalizedDifference(['Nadir_Reflectance_Band1','Nadir_Reflectance_Band5'])
.rename(
'NDVI_MOD');
return index
.copyProperties(img,['system:time_start','system:time_end','system:index']);
};
var MOD = ee.ImageCollection('MODIS/006/MCD43A4')
.filterBounds(geometry)
.filterDate('2018-10-24','2019-06-30')
.map(M_ndvi);
var MODIS = ee.ImageCollection(MOD)
.filter(ee.Filter.date(START, END))
.map(addTime)
.filter(ee.Filter.inList('Date',ee.List(DATES)));
print(MODIS);
var S2_and_MOD = S2_resampled.combine(MODIS, false);
print(S2_and_MOD);
var Diff = S2_and_MOD.map(function(img){
var clip = img.clip(geometry);
var Diffe = clip.expression('NDVI_S2 - NDVI_MOD',
{'NDVI_S2':clip.select('NDVI_S2') ,
'NDVI_MOD':clip.select('NDVI_MOD')}).rename('Diff');
return Diffe
.copyProperties(img,['system:time_start','system:time_end']); });
print(Diff);
ee.Image.combine() uses the system:ID property to join the 2 images. See the documentation here. Since your images do not match, the resulting collection has no images.
A solution that should fit your needs utilizes the ee.Join.inner() to take advantage of the Date property that you have created to join the 2 image collections. A similar question was answered here.
Using inner join, I was able to accomplish what appeared to be your goal of finding the difference in NDVI between the S2 and MODIS collections. The full working script can be found here: https://code.earthengine.google.com/dc45df1b7cf83723d53e9f7917975e2d
Code:
// Function - Calculate S2 NDVI
var ndvi = function(img){
var bands = img.select(['B2','B3','B4','B8']).multiply(0.0001)
.clip(geometry);
var index = bands.normalizedDifference(['B8','B4']).rename('NDVI_S2');
return index
.copyProperties(img,['system:time_start','system:time_end','system:index']);
};
// Get S2 NDVI images
var S2 = ee.ImageCollection('COPERNICUS/S2_SR')
.filterBounds(geometry)
.filterDate('2018-10-24','2019-06-30')
//.filter(ee.Filter.lte('CLOUDY_PIXEL_PERCENTAGE',20))
.map(ndvi);
print('S2 NDVI ImageCollection',S2);
// Set Date Parameters
var START = '2018-10-24';
var END = '2019-06-30';
// Create Date List
var DATES = [ '2018-12-19', '2018-12-29', '2019-01-23', '2019-02-12', '2019-03-04',
'2019-03-19', '2019-04-08', '2019-04-13', '2019-05-13', '2019-05-18', '2019-05-23',
'2019-05-28', '2019-06-02', '2019-06-07', '2019-06-12', '2019-06-17', '2019-06-22',
'2019-06-27'];
// Function - Add 'Date' field to image
var addTime = function(x) {
return x.set('Date', ee.Date(x.get('system:time_start')).format("YYYY-MM-dd"))};
// Run addTime on S2 ImageCollection
var Sentinel = ee.ImageCollection(S2)
.filter(ee.Filter.date(START, END))
.map(addTime)
.filter(ee.Filter.inList('Date',ee.List(DATES)));
print('Date Added S2', Sentinel);
// Get MODIS Projection
var PMODIS = ee.Image('MODIS/006/MCD43A4/2018_12_19').select('Nadir_Reflectance_Band4');
var MODProjection = PMODIS.projection();
print('MODIS projection:', MODProjection);
// Set Visualization Parameters
var Viz = {min: 0, max: 1, palette: ['be6c44','ca3a3a','e4ae0c','565c04','819536']};
// Reproject S2 images to MODIS projection
var S2_resampled = Sentinel.map(function(img){
var S2Mean = img
// Force the next reprojection to aggregate instead of resampling.
.reduceResolution({
reducer: ee.Reducer.mean(),
maxPixels: 2146
})
// Request the data at the scale and projection of the Sentinel image.
.reproject({
crs: MODProjection
});
return S2Mean
.copyProperties(img,['system:time_start','system:time_end','system:index']);
});
print('S2_resampled',S2_resampled);
Map.addLayer(S2_resampled);
// Function - Calculate MODIS NDVI
var M_ndvi = function(img){
var bands = img.select(['Nadir_Reflectance_Band1','Nadir_Reflectance_Band5']).multiply(0.0001)
.clip(geometry);
var index = bands.normalizedDifference(['Nadir_Reflectance_Band1','Nadir_Reflectance_Band5']).rename('NDVI_MOD');
return index
.copyProperties(img,['system:time_start','system:time_end','system:index']);
};
// Get MODIS NDVI Images
var MOD = ee.ImageCollection('MODIS/006/MCD43A4')
.filterBounds(geometry)
.filterDate('2018-10-24','2019-06-30')
.map(M_ndvi);
// Run addTime on MODIS ImageCollection
var MODIS = ee.ImageCollection(MOD)
.filter(ee.Filter.date(START, END))
.map(addTime)
.filter(ee.Filter.inList('Date',ee.List(DATES)));
print('MODIS',MODIS);
// Combine MODIS and S2 Image Collections using Date
// Specify the join type
var join_type = ee.Join.inner();
// Set the join parameter
var filter = ee.Filter.equals({
leftField: 'Date',
rightField: 'Date'
});
// Execute the join
var inner_join = ee.ImageCollection(join_type.apply(MODIS,S2_resampled,filter));
// Flatten joined images into a single image with 2 bands
var S2_and_MOD = inner_join.map(function(feature) {
return ee.Image.cat(feature.get('primary'), feature.get('secondary'));
});
print('Combined S2 and MODIS Collection:',S2_and_MOD);
// Calculate the difference between S2 and MODIS NDVI values
var Diff = S2_and_MOD.map(function(img){
var clip = img.clip(geometry);
var Diffe = clip.expression('NDVI_S2 - NDVI_MOD',
{'NDVI_S2':clip.select('NDVI_S2') , 'NDVI_MOD':clip.select('NDVI_MOD')}).rename('Diff');
return Diffe
.copyProperties(img,['system:time_start','system:time_end']); });
print('NDVI Difference Collection',Diff);
I am using jquery easyui edatagrid, where one column is of datebox type editor.
I want to auto select today date so that data entry is faster.
Code :
<th field="date" width="50" editor="{type:'datebox',options:{formatter:myformatter,parser:myparser,required:true}}">Date</th>
function myformatter(date){
var y = date.getFullYear();
var m = date.getMonth()+1;
var d = date.getDate();
return (d<10?('0'+d):d)+'/'+(m<10?('0'+m):m)+'/'+ y;
}
function myparser(s){
if (!s) return new Date();
var ss = (s.split('/'));
var d = parseInt(ss[0],10);
var m = parseInt(ss[1],10);
var y = parseInt(ss[2],10);
if (!isNaN(y) && !isNaN(m) && !isNaN(d)){
return new Date(y,m-1,d);
} else {
return new Date();
}
}
You can set the date as soon as the grid data is loaded. For example, something like
$('.datebox input').each( function(){ $(this).val(formatDate(new Date())) });
It is a matter of getting the input fields. For me the above works, you can adjust it according to your code. Then you need a function that does the date formatting, for example
function formatDate(value) {
return value.getMonth()+1 + "/" + value.getDate() + "/" + value.getYear();
}
I have two arrays containing latitude and longtitude of 7 locations,and I use the following
code for getting the location of these 7 points:
var geocoder;
initialize();
codeLatLng();
function initialize() {
geocoder = new google.maps.Geocoder();
}
function codeLatLng() {
var arrlat=[45.95268273, 47.00196833,45.99168238, 46.2186456, 45.91612197, 45.91606814, 45.91606814];
var arrlon=[-66.68426012, -65.56480221, -63.98068545, -64.44419501, -66.74801471, -66.74810832, -66.74810832];
var input = document.getElementById("latlng").getAttribute('value');
console.log(input);
var latlngStr = input.split(",", 2);
var lat = parseFloat(latlngStr[0]);
var lng = parseFloat(latlngStr[1]);
for(var i=0;i<arrlat.length;i++)
{
var latlng = new google.maps.LatLng(arrlat[i], arrlon[i]);
geocoder.geocode({
'latLng': latlng
}, function(results, status) {
//document.getElementById("test").innerHTML = '' + (results[4].formatted_address); + ''
alert(results[4].formatted_address);
});
}
}
whenever I feed the arrays with 5 of less elements the code works properly but for more than 5 I get 5 alert showing the location of the first 5 elements but for the last 2 I get the following error:
Uncaught TypeError: Cannot read property '4' of null
And here is the Jfiddle link:
link
Can anyone help?
Code more defensively. Check the status of the response before using it. If it isn't "OK", there won't be any results to process.
function codeLatLng() {
var arrlat=[45.95268273, 47.00196833,45.99168238, 46.2186456, 45.91612197, 45.91606814, 45.91606814];
var arrlon=[-66.68426012, -65.56480221, -63.98068545, -64.44419501, -66.74801471, -66.74810832, -66.74810832];
var input = document.getElementById("latlng").getAttribute('value');
console.log(input);
var latlngStr = input.split(",", 2);
var lat = parseFloat(latlngStr[0]);
var lng = parseFloat(latlngStr[1]);
for(var i=0;i<arrlat.length;i++)
{
var latlng = new google.maps.LatLng(arrlat[i], arrlon[i]);
geocoder.geocode({
'latLng': latlng
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK ) {
//document.getElementById("test").innerHTML = '' + (results[4].formatted_address); + ''
if (results.length >= 5)
alert(results[4].formatted_address);
else alert("less than 5 results");
} else alert("reverse geocode failed, status="+status);
});
}
}
See the documentation on Status Codes for what the failure codes mean.
I have Yandex map tiles (Russian) working in Google Maps API v2 but something's not working in Google Maps API v3, see the following jsfiddle: http://jsfiddle.net/VkGjq/1/
Note that when switching between the Google road map and the Yandex tiles they don't line up & the marker is in the wrong position.
For Maps v2, I made an equivalent jsfiddle but it's broken since it needs an API key: http://jsfiddle.net/ggrgQ/1/
You can see similar code here, but you will have to navigate to Moscow manually as Yandex doesn't have any decent data outside of Russia: http://gpsloglabs.com/share/2367c16f3a0e75b05ac8a5529afba225dd929518/
I don't recall where I got the v3 code, but the constants appear to roughly correspond to the v2 version. Other than that, I don't understand what the projection is doing so I'm stuck.
Any ideas?
The code from the jsfiddle is as follows:
var center = new google.maps.LatLng(55.75, 37.62);
var mapOptions = {
zoom: 10,
center: center,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map'), mapOptions);
new google.maps.Marker({map: map, position: center});
map.mapTypes.set("Yandex",
new google.maps.ImageMapType(
{getTileUrl: function(coord, zoom) {
return "http://vec0"+((coord.x+coord.y)%5)+".maps.yandex.net/tiles?l=map&v=2.16.0&x=" +
coord.x + "&y=" + coord.y + "&z=" + zoom + "";
},
tileSize: new google.maps.Size(256, 256),
isPng: true,
alt: "Yandex",
name: "Yandex",
projection: new YandexProjection(),
maxZoom: 17}));
map.setOptions({mapTypeControlOptions: {mapTypeIds: [google.maps.MapTypeId.ROADMAP, "Yandex"]} });
function YandexProjection() {
this.pixelOrigin_ = new google.maps.Point(128,128);
var MERCATOR_RANGE = 256;
this.pixelsPerLonDegree_ = MERCATOR_RANGE / 360;
this.pixelsPerLonRadian_ = MERCATOR_RANGE / (2 * Math.PI);
this.fromLatLngToPoint = function(latLng) {
function atanh(x) {
return 0.5*Math.log((1+x)/(1-x));
}
function degreesToRadians(deg) {
return deg * (Math.PI / 180);
}
function bound(value, opt_min, opt_max) {
if (opt_min != null) value = Math.max(value, opt_min);
if (opt_max != null) value = Math.min(value, opt_max);
return value;
}
var origin = this.pixelOrigin_;
var exct = 0.0818197;
var z = Math.sin(latLng.lat()/180*Math.PI);
return new google.maps.Point(origin.x + latLng.lng() *this.pixelsPerLonDegree_,
Math.abs(origin.y - this.pixelsPerLonRadian_*(atanh(z)-exct*atanh(exct*z))));
};
this.fromPointToLatLng = function(point) {
var origin = this.pixelOrigin_;
var lng = (point.x - origin.x) / this.pixelsPerLonDegree_;
var latRadians = (point.y - origin.y) / -this.pixelsPerLonRadian_;
var lat = Math.abs((2*Math.atan(Math.exp(latRadians))-Math.PI/2)*180/Math.PI);
var Zu = lat/(180/Math.PI);
var Zum1 = Zu+1;
var exct = 0.0818197;
var yy = -Math.abs(((point.y)-128));
while (Math.abs(Zum1-Zu)>0.0000001){
Zum1 = Zu;
Zu = Math.asin(1-((1+Math.sin(Zum1))*Math.pow(1-exct*Math.sin(Zum1),exct))
/ (Math.exp((2*yy)/-(256/(2*Math.PI)))*Math.pow(1+exct*Math.sin(Zum1),exct)));
}
if (point.y>256/2) {
lat=-Zu*180/Math.PI;
} else {
lat=Zu*180/Math.PI;
}
return new google.maps.LatLng(lat, lng);
};
return this;
}
It turns out that the projection property can't be set via the ImageMapTypeOptions and has to be assigned after the ImageMapType has been constructed, this jsfiddle now works: http://jsfiddle.net/VkGjq/2/
var yandexMapType = new google.maps.ImageMapType(
{getTileUrl: function(coord, zoom) {
return "http://vec0"+((coord.x+coord.y)%5)+".maps.yandex.net/tiles?l=map&v=2.16.0&x=" +
coord.x + "&y=" + coord.y + "&z=" + zoom + "";
},
tileSize: new google.maps.Size(256, 256),
isPng: true,
alt: "Yandex",
name: "Yandex",
maxZoom: 17});
// projection is ignored if passed to MapTypeOptions
yandexMapType.projection = new YandexProjection();
map.mapTypes.set("Yandex", yandexMapType);
By license agreement you can't use yandex maps without yandex api. You can't use yandex tiles in leaflet.
You need to wrap yandex api or use http://leafletjs.com/plugins.html
Or write own a wrapper.
Example https://all-maps.herokuapp.com/
https://github.com/artamonovdev/all-maps