max-pub
1/22/2018 - 6:48 PM

GEO tools

gps = (callback) => {
    // .watchPosition     .getCurrentPosition
    var out = {};
    navigator.geolocation.watchPosition((pos) => {
        var tmp = {
            lat: pos.coords.latitude.toFixed(5) * 1,
            lon: pos.coords.longitude.toFixed(5) * 1,
            acc: pos.coords.accuracy
        }
        if (tmp.lat == out.lat && tmp.lon == out.lon) return;
        out = tmp;
        callback(out);
    }, (error) => {
        console.error('gps.error', error)
    });
}
mapSearch = (query) => {
    return new Promise((resolve, reject) => {
        fetch("https://maps.google.com/maps/api/geocode/json?sensor=true&address=" + query)
            .then((resp) => resp.json())
            .then(function(data) {
                let types = {
                    country: 'country',
                    administrative_area_level_1: 'state',
                    administrative_area_level_2: 'county',
                    locality: 'city',
                    sublocality: 'quarter',
                    neighborhood: 'neighborhood',
                    route: 'street',
                    street_number: 'streetNumber',
                    postal_code: 'zipCode',
                    street_address: 'street',
                    postal_town: 'city'
                };
                var list = [];
                for (var i in data.results) {
                    var dat = data.results[i];
                    var location = {};
                    var address = dat.address_components;
                    for (var part in address) {
                        var typ = address[part].types[0];
                        //            console.log('part',address[part]);
                        if (types[typ]) location[types[typ]] = address[part].long_name;
                        if (types[typ]) location[types[typ] + 'Code'] = address[part].short_name;
                        if (location[types[typ]] == location[types[typ] + 'Code']) delete location[types[typ] + 'Code'];
                    }
                    location.string = dat.formatted_address;
                    location.lat = dat.geometry.location.lat.toFixed(5) * 1;
                    location.lon = dat.geometry.location.lng.toFixed(5) * 1;
                    location.type = types[dat.types[0]];
                    //        console.log("TYP:",dat.types[0],' -> ',location.type);
                    list.push(location);
                }
                resolve(list);
                // return list;
            });
    });
}