Last active
September 12, 2019 02:08
-
-
Save jkao/be493abd078151226c50e9e84d611466 to your computer and use it in GitHub Desktop.
A wrapper for a C++ class exposed in JavaScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* s2cellid.h */ | |
#include <napi.h> | |
#include "s2/s2latlng.h" | |
class LatLng : public Napi::ObjectWrap<LatLng> { | |
public: | |
LatLng(const Napi::CallbackInfo& info); | |
static Napi::FunctionReference constructor; | |
static Napi::Object Init(Napi::Env env, Napi::Object exports); | |
private: | |
Napi::Value ToString(const Napi::CallbackInfo &info); | |
S2LatLng s2latlng; | |
}; | |
/* | |
* s2cellid.cc | |
* | |
* Usage in JavaScript: | |
* const s2 = require('@radarlabs/s2'); | |
* const ll = new s2.LatLng(48.8584, 2.2945); | |
* ll.toString(); // "48.8584,2.2945" | |
*/ | |
#include "latlng.h" | |
Napi::FunctionReference LatLng::constructor; | |
Napi::Object LatLng::Init(Napi::Env env, Napi::Object exports) { | |
Napi::HandleScope scope(env); | |
Napi::Function func = DefineClass(env, "LatLng", { | |
InstanceMethod("toString", &LatLng::ToString) | |
}); | |
constructor = Napi::Persistent(func); | |
constructor.SuppressDestruct(); | |
exports.Set("LatLng", func); | |
return exports; | |
} | |
LatLng::LatLng(const Napi::CallbackInfo& info) : Napi::ObjectWrap<LatLng>(info) { | |
Napi::Env env = info.Env(); | |
Napi::HandleScope scope(env); | |
int length = info.Length(); | |
if (length <= 0 || !info[0].IsNumber() || !info[1].IsNumber()) { | |
Napi::TypeError::New(env, "(lat: number, lng: number) expected.").ThrowAsJavaScriptException(); | |
return; | |
} | |
Napi::Number lat = info[0].As<Napi::Number>(); | |
Napi::Number lng = info[1].As<Napi::Number>(); | |
this->s2latlng = S2LatLng::FromDegrees( | |
lat.DoubleValue(), | |
lng.DoubleValue() | |
); | |
} | |
Napi::Value LatLng::ToString(const Napi::CallbackInfo& info) { | |
return Napi::String::New(info.Env(), this->s2latlng.ToStringInDegrees()); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment