Skip to content

Instantly share code, notes, and snippets.

@jamlfy
Created July 18, 2019 20:33
Show Gist options
  • Save jamlfy/ef1465d1c49f149bd69216f8679fb931 to your computer and use it in GitHub Desktop.
Save jamlfy/ef1465d1c49f149bd69216f8679fb931 to your computer and use it in GitHub Desktop.
Array.prototype.flatten = function() {
var output = [],
value;
for (var i = this.length - 1; i >= 0; i--) {
if (Array.isArray(this[i]) && this[i].length > 0) {
value = this[i].flatten();
for (var f = 0; f < value.length; f++) output.push(value[f]);
} else if (!Array.isArray(this[i])) {
output.push(this[i]);
}
}
return output;
};
/**
* Sets/Gets Cookies
*/
Object.defineProperty(document, "Cookie", {
/**
* Get the cookies
* @return {Object} { [nameCookie] : [valueCookie] }
*/
get: function() {
var jar = {};
var cookies = document.cookie ? document.cookie.split("; ") : [];
for (var i = 0; i < cookies.length; i++) {
var parts = cookies[i].split("=");
var name = parts[0];
var value = parts.slice(1).join("=");
if (value.charAt(0) === '"') {
value = value.slice(1, -1);
}
try {
if (/^[\{\[]/.test(value)) {
value = JSON.parse(value);
}
} catch (e) {
} finally {
jar[name] = value;
}
}
return jar;
},
/**
* Set Cookie
* @param {Object} cookie
*/
set: function(cookie) {
if (!cookie.key) {
throw "No exist key/value";
}
cookie.path = "/";
if (typeof cookie.expires === "number" && cookie.expires != NaN) {
cookie.expires = new Date(new Date() * 1 + cookie.expires * 864e5);
}
cookie.expires = cookie.expires ? cookie.expires.toUTCString() : "";
try {
var result = JSON.stringify(cookie.value || "");
if (/^[\{\[]/.test(result)) {
cookie.value = result;
}
} catch (e) {}
cookie.value = encodeURIComponent(String(cookie.value)).replace(
/%(23|24|26|2B|3A|3C|3E|3D|2F|3F|40|5B|5D|5E|60|7B|7D|7C)/g,
decodeURIComponent
);
cookie.key = encodeURIComponent(String(cookie.key))
.replace(/%(23|24|26|2B|5E|60|7C)/g, decodeURIComponent)
.replace(/[\(\)]/g, escape);
var stringifiedCookie = "";
for (var attrName in cookie) {
if (!cookie[attrName] || attrName == "key" || attrName == "value") {
continue;
}
stringifiedCookie += "; " + attrName;
if (cookie[attrName] === true) {
continue;
}
stringifiedCookie += "=" + cookie[attrName].split(";")[0];
}
return (document.cookie =
cookie.key + "=" + cookie.value + stringifiedCookie);
}
});
/**
* Select the city by params
* * IP
* * HTML/geolocation
*
* The event send is
*
* ```typescript
* interface Event = {
* to : string,
* from? : string,
* lat? : number,
* lng? : number,
* city? : string,
* };
* ```
* jQuery.geoSelect.start();
*/
jQuery.geoSelect = {
/**
* Name Cookie
* @type {String}
*/
cookieName: "wordpress_prefered_location",
/**
* Array the cites actives in the topbar
* @type {<{ key: string, value: string }>[]}
*/
cities: [],
/**
* Element of google geocoder
* @type {google}
*/
geocoder: null,
/**
* Start the geocode
*/
start: function() {
if (!document.Cookie[jQuery.geoSelect.cookieName]) {
jQuery.geoSelect.geocoder = new google.maps.Geocoder();
var cities = jQuery("#prefered-location > option").map(function(e, w) {
var ele = jQuery(w);
return { key: ele.val(), value: ele.text() };
});
for (var i = cities.length - 1; i >= 0; i--) {
jQuery.geoSelect.cities.push(cities[i]);
}
jQuery.geoSelect.send({
to: "ip"
});
}
},
/**
* Send events
* @param {Event} e
*/
send: function(e) {
if (jQuery.geoSelect[e.to]) {
jQuery.geoSelect[e.to](e);
} else if (e.lat && e.lng) {
jQuery.geoSelect.city(e);
}
},
/**
* The end geoSelect, create a cookie
* @param {Event} e
*/
end: function(e) {
var hide = true;
if (e.city) {
hide = window.confirm(
"Hemos detectado que se encuentra en " +
e.city.value +
", Quiere buscar en esta localizacion?"
);
}
if (hide && e.city && e.city.key) {
document.Cookie = {
key: jQuery.geoSelect.cookieName,
value: e.city.key,
expires: 2
};
} else {
jQuery(".content-options").toggleClass("content-options-show");
}
},
/**
* Get the location form the IP
* @param {Event} e
*/
ip: function(e) {
var key = /[?&]key(=([^&#]*)|&|#|$)/.exec(
jQuery("script[src*=google]")
.last()
.attr("src")
);
if (key && key[2]) {
jQuery.ajax({
url:
"https://www.googleapis.com/geolocation/v1/geolocate?key=" + key[2],
data: JSON.stringify({ considerIp: "true" }),
type: "POST",
contentType: "application/json",
success: function(data) {
if (data.location) {
jQuery.geoSelect.send(
Object.assign({ to: "city", from: "location" }, data.location)
);
} else {
jQuery.geoSelect.send({ to: "location" });
}
},
error: function(argument) {
jQuery.geoSelect.send({ to: "location" });
}
});
} else {
jQuery.geoSelect.send({ to: "location" });
}
},
/**
* Get the location form API HTML
* @param {Event} e
*/
location: function(e) {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(
function(position) {
jQuery.geoSelect.send({
to: "city",
from: "end",
lat: position.coords.latitude,
lng: position.coords.longitude
});
},
function() {
window.alert("No econtramos ninguna ubicacion");
jQuery.geoSelect.send({
to: "end"
});
}
);
} else {
jQuery.geoSelect.send({
to: "end"
});
}
},
/**
* Get the City from the lng/lat
* @param {Event} e
*/
city: function(e) {
jQuery.geoSelect.geocoder.geocode(
{
latLng: new google.maps.LatLng(e.lat, e.lng)
},
function(results, status) {
var city;
if (status == google.maps.GeocoderStatus.OK) {
var all = results
.map(function(e) {
return [
e.address_components.map(z => z.long_name),
e.address_components.map(z => z.short_name)
];
})
.flatten();
city = jQuery.geoSelect.cities.find(function(w) {
return all.indexOf(w.value) >= 0;
});
}
jQuery.geoSelect.send({
to: city && city.key ? "end" : e.from,
city: city
});
}
);
}
};
function initGeoSelector() {
if (jQuery.geoSelect && jQuery.geoSelect.start) {
jQuery.geoSelect.start();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment