Skip to content

Instantly share code, notes, and snippets.

@dalelane
Created April 10, 2024 22:39
Show Gist options
  • Save dalelane/6386cb7f9553945808141a46e9284adc to your computer and use it in GitHub Desktop.
Save dalelane/6386cb7f9553945808141a46e9284adc to your computer and use it in GitHub Desktop.
class Scratch3ML4KMap {
constructor() {
this.EARTH_RADIUS = 6371;
this.TOP_LEFT = {
mapCoordsX : -240, mapCoordsY : 180,
lat : 40.0, lon : -123.5
};
this.BOTTOM_RIGHT = {
mapCoordsX : 50, mapCoordsY : -180,
lat : 32.5, lon : -116.0
};
this.TOP_LEFT_POS = this._latlonToGlobalCoords(this.TOP_LEFT.lat, this.TOP_LEFT.lon);
this.BOTTOM_RIGHT_POS = this._latlonToGlobalCoords(this.BOTTOM_RIGHT.lat, this.BOTTOM_RIGHT.lon);
this.X_RANGE = this.BOTTOM_RIGHT_POS.x - this.TOP_LEFT_POS.x;
this.Y_RANGE = this.BOTTOM_RIGHT_POS.y - this.TOP_LEFT_POS.y;
}
getInfo () {
return {
id : 'mlforkidsCaliforniaMap',
name : 'California',
blocks: [
{
opcode : 'californiaMapX',
text : 'map X coordinate for [LATITUDE] , [LONGITUDE]',
blockType : 'reporter',
arguments : {
LATITUDE : {
type : 'number',
defaultValue : 50.6787
},
LONGITUDE : {
type : 'number',
defaultValue : -1.5667
}
},
},
{
opcode : 'californiaMapY',
text : 'map Y coordinate for [LATITUDE] , [LONGITUDE]',
blockType : 'reporter',
arguments : {
LATITUDE : {
type : 'number',
defaultValue : 50.6787
},
LONGITUDE : {
type : 'number',
defaultValue : -1.5667
}
},
}
]
}
}
californiaMapX (args) {
return this._latlonToMapCoords(parseFloat(args.LATITUDE, 10), parseFloat(args.LONGITUDE, 10)).x;
}
californiaMapY (args) {
return this._latlonToMapCoords(parseFloat(args.LATITUDE, 10), parseFloat(args.LONGITUDE, 10)).y;
}
_latlonToGlobalCoords (lat, lon){
return {
x : this.EARTH_RADIUS * lon * Math.cos((this.TOP_LEFT.lat + this.BOTTOM_RIGHT.lat) / 2),
y : this.EARTH_RADIUS * lat
};
}
_latlonToMapCoords (lat, lon){
const pos = this._latlonToGlobalCoords(lat, lon);
const percentX = ((pos.x - this.TOP_LEFT_POS.x) / this.X_RANGE);
const percentY = ((pos.y - this.TOP_LEFT_POS.y) / this.Y_RANGE);
const mapDistanceX = this.BOTTOM_RIGHT.mapCoordsX - this.TOP_LEFT.mapCoordsX;
const mapDistanceY = this.BOTTOM_RIGHT.mapCoordsY - this.TOP_LEFT.mapCoordsY;
return {
x: this.TOP_LEFT.mapCoordsX + mapDistanceX * percentX,
y: this.TOP_LEFT.mapCoordsY + mapDistanceY * percentY
};
}
}
Scratch.extensions.register(new Scratch3ML4KMap());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment