I'm trying to get the name of a location from given latitude and longitude.
Is there any possibility to get it like
getNameOfLocation(longitude,latitude)?
For example getNameOfLocation(48.1471904942317, 11.591434478759765) --> results Munich
I don't want to use any graphical elements to show like Google Maps.
Any ideas?
Thanks for help
var geo = Ext.create('Ext.util.Geolocation', {
autoUpdate: false,
listeners: {
locationupdate: function(geo) {
alert('New latitude: ' + geo.getLatitude());
},
locationerror: function(geo, bTimeout, bPermissionDenied, bLocationUnavailable, message) {
if(bTimeout){
alert('Timeout occurred.');
} else {
alert('Error occurred.');
}
}
}
});
geo.updateLocation();
try this..
function getNameOfLocation(lat, lng) {
var geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(lat, lng);
geocoder.geocode({
'latLng': latlng
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
alert(results[0].formatted_address) // your result
//country name
for (var i=0; i<results[0].address_components.length; i++) {
for (var b=0;b<results[0].address_components[i].types.length;b++) {
if (results[0].address_components[i].types[b] == "administrative_area_level_1") {
city= results[0].address_components[i];
break;
}
}
}
} else {
alert("No result");
}
} else {
alert("failed: " + status);
}
});
}
You can send an Ajax request to google maps API. For Example:
http://maps.googleapis.com/maps/api/geocode/json?latlng=48.1471904942317,11.591434478759765&sensor=false
and then parse the JSON result.
Related
I want to make my form submission happen server-side in order to not expose my API key. I plan to do this with netlify functions however I don't know how that would look with Axios. I've looked for examples on how to do this but I don't seem to find any. Could some help me I'm stuck as to what to put inside my the Netlify function? If anyone has worked with these two programs and could provide a hand that would be helpful here is my javascript with my submission function.
var form = document.querySelector("#user_form");
let reqHeaders = {
headers: {
Authorization: "Bearer",
}
}
let url = ""
let reqData = {
records: [
{
fields: null
}
]
}
let formData = {
firstName: "",
lastName: "",
email: ""
}
function logData(id, dataObj, value) {
dataObj[id] = value;
console.log(value)
}
function formMessg (id) {
document.querySelector(id).style.display = "block";
setTimeout(function(){
document.querySelector(id).style.display = "none";
form.reset();
}, 2500)
}
form.addEventListener("submit", function (e) {
e.preventDefault();
let spam = document.getElementById('spam').value;
try {
for(const data in formData){
if(formData[data] === "" || spam.length !== 0){
const error = new Error();
error.notVaild = true;
throw error;
}
}
reqData.records[0].fields = formData;
console.log(reqData);
axios.post(url, reqData, reqHeaders).then((res) => {
formMessg ('.success-messg');
form.style.display = "none";
})
.catch ((err) => {
throw err;
});
} catch (err){
if (err.reponse){
formMessg ('.fail-messg');
} else if (err.request) {
formMessg ('.fail-messg');
} else if ("Notvalid") {
formMessg ('.fill-messg');
}else {
console.log(err);
}
}
});
Background:
I have a Parse database of images. Simply, my code does this:
A user, through a Parse Cloud call requests an image ("getNewPicture"). Nested within I check if he has seen any pictures before (alongside other requirements) and if so deliver one specific picture (getSpecifiedPicture). If he has not, then I deliver a new picture (getNewPicture).
Issue:
Calling "getNewPicture" through Parse Cloud Code function I get an error code 141. What's strange is that it works through Android but not iOS.
My code:
Parse.Cloud.define("getNewPicture", function(request, response) {
var SeenPictures = Parse.Object.extend("SeenPictures");
var query = new Parse.Query(SeenPictures);
var username = request.params.username;
var notWantedPics = [];
query.ascending("createdAt");
query.equalTo("username", username);
query.find({
success: function(results) {
for (var i = 0; i < results.length; i++) {
if (results[i].get("likes") == 1 || results[i].get("dislikes") == 1) {
notWantedPics.push(results[i].get("pictureId"));
results.splice(i, 1);
i--;
}
}
if (results != 0) {
getSpecifiedPicture(results[0].get("pictureId"), {
success: function(returnValue) {
response.success(returnValue);
},
error: function(error) {
response.error(error);
}
});
} else {
getNewPicture(username, notWantedPics, {
success: function(returnValue) {
response.success(returnValue);
},
error: function(error) {
response.error(error);
}
});
}
},
error: function() {
response.error(error);
}
});
});
function getSpecifiedPicture(specifiedPic, callback) {
var Pictures = Parse.Object.extend("Pictures");
var pictures = new Parse.Query(Pictures);
pictures.get(specifiedPic, {
success: function(picture) {
callback.success(picture);
},
error: function(error) {
callback.error(error);
}
});
}
function getNewPicture(username, notWantedPics, callback) {
var Pictures = Parse.Object.extend("Pictures");
var pictures = new Parse.Query(Pictures);
pictures.notEqualTo("photographerUserName", username);
pictures.notContainedIn("objectId", notWantedPics);
pictures.ascending("createdAt");
pictures.find({
success: function(results) {
if (results.length > 0) {
var object = results[0];
//Some other fancy stuff
object.save();
callback.success(object);
}
},
error: function(error) {
callback.error(error);
}
});
}
Why am I getting code 141? Any help is appreciated.
Thanks.
Your callbacks are a mess. I rewrote it to follow more of a promise chain style. Much easier to follow. Also, underscore.js is your friend. Hopefully I got your idea right.
var _ = require('underscore'); // Javascript Library
Parse.Cloud.define("getNewPicture", function(request, response) {
var username = request.params.username;
var notWantedPics = [];
if (!username) {
return response.error('No username.');
}
var query1 = new Parse.Query("SeenPictures");
query1.ascending("createdAt");
query1.equalTo("username", username);
var SeenPictures = query1.find();
return Parse.Promise.when([SeenPictures]).then(function (SeenPictures) {
SeenPictures = _.filter(SeenPictures, function (SeenPicture) {
if (SeenPicture.get("likes") == 1 || SeenPicture.get("dislikes") == 1) {
notWantedPics.push(SeenPicture.get("pictureId"));
return false;
}
else {
return true;
}
});
// notWantedPics?
if (SeenPictures > 0) {
var query2 = new Parse.Query("Pictures");
var Pictures = [query2.get(SeenPictures[0].get('pictureId'))];
}
else {
var query2 = new Parse.Query("Pictures");
query2.notEqualTo("photographerUserName", username);
query2.notContainedIn("objectId", notWantedPics);
query2.ascending("createdAt");
var Pictures = query2.find();
}
return Parse.Promise.when([Pictures]);
}).then(function (Pictures) {
if (Pictures > 0) {
// Success
return response.success(Pictures[0]);
} else {
return Parse.Promise.error("No pictures.");
}
}, function (error) {
// Error
return response.error(error);
});
});
I am trying to authenticate my social media accounts through Parse via OAuth and it authenticates fine but i keep getting a Failed with success/error was not called; my code is below, can anyone help?
Parse.Cloud.define("createNewNetwork", function(request, response) {
Parse.Cloud.useMasterKey();
//console.log(request.user.id);
userHasRole(request.user.id, 'AllUsers').then(function(hasRole){
if (hasRole){
var Network = Parse.Object.extend("Network");
var query = new Parse.Query(Network);
query.equalTo("userId", request.params.userId);
query.equalTo("owner", request.user);
query.first({useMasterKey:true}).then(function(network) {
var newNetwork;
if (!network) {
newNetwork = new Network();
var custom_acl = new Parse.ACL();
custom_acl.setWriteAccess(request.user, true);
custom_acl.setPublicReadAccess(true);
newNetwork.setACL(custom_acl);
newNetwork.set("userId", request.params.userId);
newNetwork.set("followingCount", request.params.followingCount);
newNetwork.set("owner", request.user);
newNetwork.set("userData", request.params.userData);
newNetwork.set("networkName", request.params.networkName);
newNetwork.set("screenName", request.params.screenName);
} else {
newNetwork = network;
}
newNetwork.set("tokenExpired", false);
//console.log(request.params.oAuthData["access_token"]);
if (request.params.networkName == "facebook-page") {
Parse.Cloud.httpRequest({
url: 'https://graph.facebook.com/v2.1/oauth/access_token?grant_type=fb_exchange_token&client_id=**************&client_secret=***************&fb_exchange_token='+request.params.oAuthData["access_token"],
success: function(httpResponse2) {
//console.log(httpResponse2);
if (httpResponse2.status == 200) {
var data = {};
data["access_token"] = httpResponse2.text.substring(13);
newNetwork.save({oAuthData : data}, {
success: function(savedNetwork) {
response.success(savedNetwork);
},
error: function(error) {
response.error(error);
}
});
} else {
response.error("invalid token");
}
},
error: function(httpResponse2) {
console.log(httpResponse2);
response.error('Request failed with response code ' + httpResponse2.status);
}
});
} else {
newNetwork.save({oAuthData : request.params.oAuthData}, {
success: function(savedNetwork) {
response.success(savedNetwork);
},
error: function(error) {
response.error(error);
}
});
}
});
} else {
response.error("not in role");
}
});
});
Parse.Cloud.define("fetchNetworks", function(request, response) {
var attributesToHide = ["oAuthData"];
Parse.Cloud.useMasterKey();
userHasRole(request.user.id, 'AllUsers').then(function(hasRole){
if (hasRole){
var Network = Parse.Object.extend("Network");
var query = new Parse.Query(Network);
query.descending("followingCount");
var user = new Parse.User();
user.id = request.params.userToFetch;
user.fetch({}).then(function(user) {
query.equalTo("owner", user);
query.find().then(function(networks) {
networks.forEach(function(network) {
attributesToHide.forEach(function(attr) {
delete network.attributes[attr];
});
});
return response.success(networks);
});
});
} else{
response.success({super: false});
}
});
});
Line No - 101 - Removal of return should work.
Hi I am using the following code to display the user current position on the map:
function drawMap() {
var latlng = new google.maps.LatLng(currentLatitude, currentLongitude);
myLatLng = latlng;
var mapOptions = {
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
zoomControl: true,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.SMALL,
position: google.maps.ControlPosition.LEFT_TOP
},
};
if (boolTripTrack === true) {
_map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
}
}
var suc = function(p) {
console.log("geolocation success", 4);
//Draws the map initially
if (_map === null) {
currentLatitude = p.coords.latitude;
currentLongitude = p.coords.longitude;
drawMap();
//reverseGeocode(currentLatitude, currentLongitude);
} else {
myLatLng = new google.maps.LatLng(p.coords.latitude, p.coords.longitude);
}
//Creates a new google maps marker object for using with the pins
if ((myLatLng.toString().localeCompare(oldLatLng.toString())) !== 0) {
//Create a new map marker
var Marker = new google.maps.Marker({
position: myLatLng,
map: _map
});
if (_llbounds === null) {
//Create the rectangle in geographical coordinates
_llbounds = new google.maps.LatLngBounds(new google.maps.LatLng(p.coords.latitude, p.coords.longitude)); //original
} else {
//Extends geographical coordinates rectangle to cover current position
_llbounds.extend(myLatLng);
}
//Sets the viewport to contain the given bounds & triggers the "zoom_changed" event
_map.fitBounds(_llbounds);
}
oldLatLng = myLatLng;
};
var fail = function() {
console.log("Geolocation failed. \nPlease enable GPS in Settings.", 1);
};
var getLocation = function() {
console.log("in getLocation", 4);
};
This works fine but I need to perform reverse geocoding when a button is pressed so that the address is displayed. The function is am using is:
function reversegeocode(){
var latlng = new google.maps.LatLng(?, ?);
var geocoder = new google.maps.Geocoder();
geocoder.geocode({'latLng': latlng}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
alert(results[1].formatted_address);
} else {
alert('No results found');
}
} else {
alert('Geocoder failed due to: ' + status);
}
});
}
I am unsure of how to pass in the current latitude and longitude from the previous function. Can anyone help me with this??
Thank you..
Define the reverse geocode function like this, with parameters for lat and lng:
function reversegeocode(lat, lng){
var latlng = new google.maps.LatLng(lat, lng);
var geocoder = new google.maps.Geocoder();
geocoder.geocode({'latLng': latlng}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
alert(results[1].formatted_address);
} else {
alert('No results found');
}
} else {
alert('Geocoder failed due to: ' + status);
}
});
}
And then call the function by passing the variables : reverseGeocode(currentLatitude, currentLongitude);
How can I display ModelState errors returned by JSON?
I want to do something like this:
if (!ValidateLogOn(Name, currentPassword))
{
ModelState.AddModelError("_FORM", "Username or password is incorrect.");
//Return a json object to the javascript
return Json(new { ModelState });
}
What must be my code in the view to read the ModelState errors and display them?
My actual code in the view to read the JSON values is as follows:
function createCategoryComplete(e) {
var obj = e.get_object();
alert(obj.Values);
}
This is draft code but the same idea works for me in production.
The main idea here is that Json errors have predefined tag names, that no normal objects will have. For errors validation errors HTML is re-created using JavaScript (both top summary and form elements highlighting).
Server side:
public static JsonResult JsonValidation(this ModelStateDictionary state)
{
return new JsonResult
{
Data = new
{
Tag = "ValidationError",
State = from e in state
where e.Value.Errors.Count > 0
select new
{
Name = e.Key,
Errors = e.Value.Errors.Select(x => x.ErrorMessage)
.Concat(e.Value.Errors.Where(x => x.Exception != null).Select(x => x.Exception.Message))
}
}
};
}
in action:
if (!ModelState.IsValid && Request.IsAjaxRequest())
return ModelState.JsonValidation();
Client side:
function getValidationSummary() {
var el = $(".validation-summary-errors");
if (el.length == 0) {
$(".title-separator").after("<div><ul class='validation-summary-errors ui-state-error'></ul></div>");
el = $(".validation-summary-errors");
}
return el;
}
function getResponseValidationObject(response) {
if (response && response.Tag && response.Tag == "ValidationError")
return response;
return null;
}
function CheckValidationErrorResponse(response, form, summaryElement) {
var data = getResponseValidationObject(response);
if (!data) return;
var list = summaryElement || getValidationSummary();
list.html('');
$.each(data.State, function(i, item) {
list.append("<li>" + item.Errors.join("</li><li>") + "</li>");
if (form && item.Name.length > 0)
$(form).find("*[name='" + item.Name + "']").addClass("ui-state-error");
});
}
$.ajax(... function(response) {
CheckValidationErrorResponse(xhr.responseText); } );
Why not return the original ModelState object to the client, and then use jQuery to read the values. To me it looks much simpler, and uses the common data structure (.net's ModelState)
C#:
return Json(ModelState);
js:
var message = "";
if (e.response.length > 0) {
$.each(e.response, function(i, fieldItem) {
$.each(fieldItem.Value.Errors, function(j, errItem) {
message += errItem.ErrorMessage;
});
message += "\n";
});
alert(message);
}
this is a tiny tweak to queen3's client side code which handles specific validation messages, and creates a similar document to that created by MVC3:
function getValidationSummary() {
var $el = $(".validation-summary-errors > ul");
if ($el.length == 0) {
$el = $("<div class='validation-summary-errors'><ul></ul></div>")
.hide()
.insertBefore('fieldset:first')
.find('ul');
}
return $el;
}
function getResponseValidationObject(response) {
if (response && response.Tag && response.Tag == "ValidationError")
return response;
return null;
}
function isValidationErrorResponse(response, form, summaryElement) {
var $list,
data = getResponseValidationObject(response);
if (!data) return false;
$list = summaryElement || getValidationSummary();
$list.html('');
$.each(data.State, function (i, item) {
var $val, lblTxt, errorList ="";
if (item.Name) {
$val = $(".field-validation-valid,.field-validation-error")
.first("[data-valmsg-for=" + item.Name + "]")
.removeClass("field-validation-valid")
.addClass("field-validation-error");
$("input[name=" + item.Name + "]").addClass("input-validation-error")
lblTxt = $("label[for=" + item.Name + "]").text();
if (lblTxt) { lblTxt += ": "; }
}
if ($val.length) {
$val.text(item.Errors.shift());
if (!item.Errors.length) { return; }
}
$.each(item.Errors, function (c,val) {
errorList += "<li>" + lblTxt + val + "</li>";
});
$list.append(errorList);
});
if ($list.find("li:first").length) {$list.closest("div").show(); }
return true;
}
See below for code with a few amendments to Brent's answer. CheckValidationErrorResponse looks for the Validation Summary regardless of whether it's in the valid or invalid state, and inserts it if not found. If validation errors are found in the response, it applies the validation-summary-errors class to the Summary, else it applies validation-summary-valid. It assumes CSS is present to control the visibility of the Summary.
The code clears existing instances of field-validation-error, and reapplies them for errors found in the response.
function getValidationSummary(form) {
var $summ = $(form).find('*[data-valmsg-summary="true"]');
if ($summ.length == 0)
{
$summ = $('<div class="validation-summary-valid" data-valmsg-summary="true"><ul></ul></div>');
$summ.appendTo(form);
}
return $summ;
}
function getValidationList(summary) {
var $list = $(summary).children('ul');
if ($list.length == 0) {
$list = $('<ul></ul>');
$list.appendTo(summary);
}
return $list;
}
function getResponseValidationErrors(data) {
if (data && data.ModelErrors && data.ModelErrors.length > 0)
return data.ModelErrors;
return null;
}
function CheckValidationErrorResponse(data, form, summaryElement) {
var errors = getResponseValidationErrors(data);
var $summ = summaryElement || getValidationSummary(form);
var $list = getValidationList($summ);
$list.html('');
$(form).find(".field-validation-error")
.removeClass("field-validation-error")
.addClass("field-validation-valid");
if (!errors)
{
$summ.removeClass('validation-summary-errors').addClass('validation-summary-valid');
return false;
}
$.each(errors, function (i, item) {
var $val, $input, errorList = "";
if (item.Name) {
$val = $(form).find(".field-validation-valid, .field-validation-error")
.filter("[data-valmsg-for=" + item.Name + "]")
.removeClass("field-validation-valid")
.addClass("field-validation-error");
$input = $(form).find("*[name='" + item.Name + "']");
if (!$input.is(":hidden") && !$val.length)
{
$input.parent().append("<span class='field-validation-error' data-valmsg-for='" + item.Name + "' data-valmsg-replace='false'>*</span>");
}
$input.addClass("input-validation-error");
}
$.each(item.Errors, function (c, err) {
errorList += "<li>" + err + "</li>";
});
$list.append(errorList);
});
$summ.removeClass('validation-summary-valid').addClass('validation-summary-errors');
return true;
}
C#
public class ValidateModelAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
if (actionContext.ModelState.IsValid == false)
{
actionContext.Response = actionContext.Request.CreateErrorResponse(
HttpStatusCode.BadRequest, actionContext.ModelState);
}
}
}
JavaScript
$.ajax({
type: "GET",
url: "/api/xxxxx",
async: 'false',
error: function (xhr, status, err) {
if (xhr.status == 400) {
DisplayModelStateErrors(xhr.responseJSON.ModelState);
}
},
....
function DisplayModelStateErrors(modelState) {
var message = "";
var propStrings = Object.keys(modelState);
$.each(propStrings, function (i, propString) {
var propErrors = modelState[propString];
$.each(propErrors, function (j, propError) {
message += propError;
});
message += "\n";
});
alert(message);
};
If you are returning JSON, you cannot use ModelState. Everything that the view needs should be contained inside the JSON string. So instead of adding the error to the ModelState you could add it to the model you are serializing:
public ActionResult Index()
{
return Json(new
{
errorControl = "_FORM",
errorMessage = "Username or password is incorrect.",
someOtherProperty = "some other value"
});
}