Can someone pls tell me what i'm doing wrong. I exported a topojson from mapshaper.org. Then I drew the map using the d3. But the map appears zoomed out(very small). How do I get it to be properly scaled and centered. Pls note that i've used some solutions on stackoverflow and I've tried fitExtent. The issue with fitExtent is that I will not be able to translate the map later when I need to. I want the loaded map to appear scaled and centered. Here's the code to draw the map
let width = 900
let height = 500
let svg = null
let chartContainer = null
// load data
let map = {}
const inputFilepath3 = '../Data/nigeria.topojson'
const data = await d3.json(inputFilepath3)
const object = data.objects.gadm36_NGA_1
map.features = topojson.feature(data, object).features
// build container
if (!svg) {
svg = d3.select('body')
.append('svg')
chartContainer = svg.append('g')
.classed('chart-container', true)
}[![enter image description here][1]][1]
svg.attr('width', width)
svg.attr('height', height)
// build scale
const colorScale = d3.scaleOrdinal(d3.schemeCategory10)
// build geopath generator
const projection = d3.geoAzimuthalEqualArea()
const geoPath = d3.geoPath(null).projection(projection)
// draw map
let ps = chartContainer.selectAll('path.state').data(map.features)
ps.exit().remove()
ps.enter().append('path').classed('state', true)
.attr('d', geoPath)
.attr('fill', function(d,i) {
return colorScale(i)
})
Related
I have profile photo of users stored in Firebase and I want to know how I can create a marker with the user's profile photo with an orange border.
I tried some code from the internet and it works but the measurements seem to be wrong and I don't know what I'm doing wrong.
The code I used:
fun setMarkerPhoto(user:User, location: Location){
var bitmapFinal : Bitmap?
if(hasProfilePhoto){
/*val options = RequestOptions()
options.centerCrop()*/
Glide.with(this)
.asBitmap()
/*.apply(options)*/
.centerCrop()
.load(user.image)
.into(object : CustomTarget<Bitmap>(){
override fun onResourceReady(resource: Bitmap, transition: com.bumptech.glide.request.transition.Transition<in Bitmap>?) {
bitmapFinal = createUserBitmapFinal(resource)
markerOptions
.position(LatLng(location!!.latitude, location!!.longitude))
.title("Current Location")
.snippet(address)
.icon(BitmapDescriptorFactory.fromBitmap(bitmapFinal))
mCurrentMarker = googleMap.addMarker(markerOptions)
}
override fun onLoadCleared(placeholder: Drawable?) {
TODO("Not yet implemented")
}
})
}else{
markerOptions
.position(LatLng(mLastLocation!!.latitude, mLastLocation!!.longitude))
.title("Current Location")
.snippet(address)
.icon(BitmapDescriptorFactory.fromBitmap(smallMarker))
mCurrentMarker = googleMap.addMarker(markerOptions)
}
}
private fun createUserBitmapFinal(bitmapInicial: Bitmap?): Bitmap? {
var result: Bitmap? = null
try {
result = Bitmap.createBitmap(150,150, Bitmap.Config.ARGB_8888) //change the size of the placeholder
result.eraseColor(Color.TRANSPARENT)
val canvas = Canvas(result)
val drawable: Drawable = resources.getDrawable(R.drawable.ic_pickup)
drawable.setBounds(0, 0, 150,150) //change the size of the placeholder, but you need to maintain the same proportion of the first line
drawable.draw(canvas)
val roundPaint = Paint(Paint.ANTI_ALIAS_FLAG)
val bitmapRect = RectF()
canvas.save()
if (bitmapInicial != null) {
val shader =
BitmapShader(bitmapInicial, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP)
val matrix = Matrix()
val scale: Float = 200 / bitmapInicial.width.toFloat() //reduce or augment here change the size of the original bitmap inside the placehoder.
// But you need to adjust the line bitmapRect with the same proportion
matrix.postTranslate(5f, 5f)
matrix.postScale(scale, scale)
roundPaint.shader = shader
shader.setLocalMatrix(matrix)
bitmapRect[10f, 10f, 104f+10f]=104f+10f //change here too to change the size
canvas.drawRoundRect(bitmapRect, 56f, 56f, roundPaint)
}
I didn't really understand how to perfectly fit the bitmap image inside the placeholder. My marker looked like this:
also the image wasn't being center cropped even though I mentioned that it should be in the code, where it says Glide.centerCrop()
Also, I'm using GeoFire to display markers of users in a specified radius of the user and for now I can display a simple marker but I want the marker to have that user's profile photo too! How can I do it?
GeoFire Code:
val geoQuery: GeoQuery = geoFire.queryAtLocation(GeoLocation(location.latitude, location.longitude), 0.5)
geoQuery.addGeoQueryEventListener(object : GeoQueryEventListener {
override fun onKeyEntered(key: String, location: GeoLocation) {
println(String.format("Key %s entered the search area at [%f,%f]", key, location.latitude, location.longitude))
Log.i("key entered","User found around you")
val aroundYou = LatLng(location.latitude, location.longitude)
if (markerList != null) {
for (marker in markerList) {
marker.remove()
}
}
otherMarkerOptions
.position(aroundYou)
.title("Current Location")
//.snippet(address)
.icon(BitmapDescriptorFactory.fromBitmap(smallMarker)) //This is a simple marker but i want it to have the user's profile photo
markerList.add(googleMap.addMarker(otherMarkerOptions))
//}
}
Thank you in advance
Edit:
In the line: val drawable: Drawable = resources.getDrawable(R.drawable.ic_pickup)
It's this png:
I want to insert the profile photo of the user on that drawable file and if the user doesn't have a profile photo then only the drawable photo will be visible.
You get the code to transform the bitmap from my code in another question in StrackOverflow. As I mentioned there, I can´t teste the code because i´m only working with flutter right now.
But looking ate your code I might try this:
Add this function:
fun dp(value: Float): Int {
return if (value == 0f) {
0
} else Math.ceil(resources.displayMetrics.density * value.toDouble()).toInt()
}
in your lines:
result = Bitmap.createBitmap(150,150, Bitmap.Config.ARGB_8888);
drawable.setBounds(0, 0, 150,150);
change to:
result = Bitmap.createBitmap(dp(62f), dp(76f), Bitmap.Config.ARGB_8888);
drawable.setBounds(0, 0, dp(150f), dp(150f)) ;
let me know the results.
I am new to Google Earth Enginge and I struggle to bring together two images in Google Earth Engine to get the areas which are in both images and the areas which are only part of one image to show forest cover change (loss, gain, no change).
My code so far which seems to at least display what I want by stacking the images above each other:
var treeCanopyCoverVis = {
min: 0.0,
max: 100.0,
palette: ['ffffff', 'afce56', '5f9c00', '0e6a00', '003800'],
};
var forest2000 = ee.ImageCollection('NASA/MEASURES/GFCC/TC/v3')
.filterDate('2000-01-01', '2000-12-31')
.select('tree_canopy_cover')
.reduce(ee.Reducer.mean());
var forest2000_ab60 = forest2000.gt(60).selfMask();
Map.addLayer(forest2000_ab60, {palette: '#d80078'}, 'Loss');
var forest2015 = ee.ImageCollection('NASA/MEASURES/GFCC/TC/v3')
.filterDate('2015-01-01', '2015-12-31')
.select('tree_canopy_cover')
.reduce(ee.Reducer.mean());
var forest2015_ab60 = forest2015.gt(60).selfMask();
Map.addLayer(forest2015_ab60, {palette: '#ebb13a'}, 'Gain');
// var loss = forest2015_ab60.intersection(forest2000_ab60);
print(forest2015_ab60);
print(forest2000_ab60);
var remain = forest2015_ab60.and(forest2000_ab60);
Map.addLayer(remain, {palette: '#746d75'}, 'Remain');
With this code the gain still includes the remain part and the loss part also still includes the remain part. I need kind of the subtraction. All functions I now tried result in errors. I appreciate any help!
How my current result looks:
I could somehow solve it with try and error.
The code:
var forest2000 = ee.ImageCollection('NASA/MEASURES/GFCC/TC/v3')
.filterDate('2000-01-01', '2000-12-31')
.select('tree_canopy_cover')
.reduce(ee.Reducer.mean());
var forest2015 = ee.ImageCollection('NASA/MEASURES/GFCC/TC/v3')
.filterDate('2015-01-01', '2015-12-31')
.select('tree_canopy_cover')
.reduce(ee.Reducer.median());
var gain = forest2000.lt(60).and(forest2015.gt(60));
Map.addLayer(gain.selfMask(), {palette: '#ebb13a'}, 'gain');
var loss = forest2000.gt(60).and(forest2015.lt(60));
Map.addLayer(loss.selfMask(), {palette: '#d80078'}, 'loss');
var nochange = forest2000.gt(60).and(forest2015.gt(60));
Map.addLayer(nochange.selfMask(), {palette: '#746d75'}, 'no change');
I am trying to use leaflet to show a smaller map than usual so I don't want to use the normal tiling system. I don't care about smooth zooming and loading higher resolution tiles when needed. Instead I am trying to add a raster image from an image file. Lets say this file that comes up when I google "hand drawn map"
So I try
download.file('https://external-preview.redd.it/7tYT__KHEh8FBKO6bsqPgC02OgLCHAFVPyjdVZI4bms.jpg?auto=webp&s=ff2fa2e448bb92c4ed6c049133f80370f306acb3',
destfile = 'map.jpg')
map = raster::raster('map.jpg')
# it seems like i need a projection to use a raster image.
# not sure what controls do I have over this, especially in
# absence of a proper map layer and it's likely
# part of the solution
crs(map) = CRS("+init=epsg:4326")
leaflet() %>%
leaflet::addRasterImage(map)
The resulting output is nothing like the input image
How do I take an arbitrary image and place in on a leaflet map?
I failed to find the exact reason why addRasterImage fails here but I found reports that it doesn't behave well on L.CRS.Simple projection, which is what you'll want to use to show a simple rectangle image.
Using htmlwidgets::onRender makes it possible to directly use the javascript function L.imageOverlay to add the image you want
library(leaflet)
# minimal custom image
imageURL = 'https://external-preview.redd.it/7tYT__KHEh8FBKO6bsqPgC02OgLCHAFVPyjdVZI4bms.jpg?auto=webp&s=ff2fa2e448bb92c4ed6c049133f80370f306acb3'
# get image data. we'll use this to set the image size
imageData =
magick::image_read(imageURL) %>% image_info()
leaflet(options = leafletOptions(crs = leafletCRS('L.CRS.Simple'))) %>%
htmlwidgets::onRender(glue::glue("
function(el, x) {
var myMap = this;
var imageUrl = '<imageURL>';
var imageBounds = [[<-imageData$height/2>,<-imageData$width/2>], [<imageData$height/2>,<imageData$width/2>]];
L.imageOverlay(imageUrl, imageBounds).addTo(myMap);
}
",.open = '<', .close = '>'))
For a large image like this if you want to make the image smaller you can either scale down using the imageBounds in javascript side or set minZoom to a negative value and use setView to start out zoomed out.
leaflet(options =
leafletOptions(crs = leafletCRS('L.CRS.Simple'),
minZoom = -1)) %>%
setView(0,0,zoom = -1) %>%
htmlwidgets::onRender(glue::glue("
function(el, x) {
var myMap = this;
var imageUrl = '<imageURL>';
var imageBounds = [[<-imageData$height/2>,<-imageData$width/2>], [<imageData$height/2>,<imageData$width/2>]];
L.imageOverlay(imageUrl, imageBounds).addTo(myMap);
}
",.open = '<', .close = '>'))
How do I use video (mp4) as alpha map in babylonJS?
In three.js applying a video as texture is as simple as assigning the video texture to alphaMap (instead of the diffuse map).
Here's the expected result in three.js - Demo.
I attempted to do the same in babylonJS to no avail. Here's what I have so far babylonJs demo
var mat = new BABYLON.StandardMaterial("mat", scene);
var videoTexture = new BABYLON.VideoTexture("video", ["textures/babylonjs.mp4", "textures/babylonjs.webm"], scene, true, true);
mat.opacityTexture = videoTexture;
Any ideas are welcome.
Thanks
You can use videoTexture.getAlphaFromRGB = true; to use all three channels combined for the alpha. By default it only uses the red channel, which does not have enough variance in the source video for it to show.
The complete example:
var mat = new BABYLON.StandardMaterial("mat", scene);
var videoTexture = new BABYLON.VideoTexture("video", ["textures/babylonjs.mp4", "textures/babylonjs.webm"], scene, true, true);
videoTexture.getAlphaFromRGB = true;
mat.opacityTexture = videoTexture;
I was wondering if there was a way to obtain the bounding box for the models that are inserted via 3dio.js, or otherwise calculate their center points? I'm looking to center them on the origin.
The images below show two models relative to the scene origin indicated by the red box.
You can access the three.js object of the 3d.io entity like this:
var threeElem = document.getElementById("custom-id").components['io3d-data3d'].data3dView.threeParent
Then you can use the native bounding box from three.js:
var bbox = new THREE.Box3().setFromObject(threeElem)
Like that you get the min/max bounds which you can use to determine the origin.
I hope that answers your question. Let me know!
Edit:
for furniture it would probably be
var threeElem = document.getElementById("custom-id").components['io3d-furniture'].data3dView.threeParent
Based on Madlaina's answer. I needed to ensure the model was loaded before
addModelToScene(type) {
let scene = document.querySelector('a-scene');
let model = document.createElement('a-entity');
model.setAttribute('io3d-data3d', getModelKey(type) )
model.addEventListener('model-loaded', () => {
// Access the three.js object of the 3d.io
let threeElem = model.components['io3d-data3d'].data3dView.threeParent
// create the bounding box
let bbox = new THREE.Box3().setFromObject(threeElem)
// Calculate the center-point offsets from the max and min points
const offsetX = (bbox.max.x + bbox.min.x)/2
const offsetY = (bbox.max.y + bbox.min.y)/2
const offsetZ = (bbox.max.z + bbox.min.z)/2
// apply the offset
model.setAttribute('position', {x:-offsetX,y:-offsetY, z:-offsetZ})
} );
scene.appendChild(model);
}
The result: