I'm new to Javascript and I'm trying to eventually make something that will get the users location in using the getLocation API with HTML5, and use simpleGeo to get the building of the coordinates.
So far I'm trying to get SimpleGeo working and I have this:
var client = new simplegeo.ContextClient('YUpXKUcaTr2ZE5T5vkhaDRAXWbDbaZts');
function displayData(err, data) {
if (err) {
console.error(err);
} else {
console.log(JSON.stringify(data));
}
}
client.getLocation({enableHighAccuracy: true}, function(err, position) {
if (err) {
// Could not retrieve location information. Check err for more information
} else {
// Latitude and longitude available in position.coords
var lat = position.coords.latitude;
var lon = position.coords.longitude;
$('#header').html('<p>your latitude is: ' + lat + '. And your longitude is: ' + lon + '.</p>');
}
});
client.getNearbyAddress(37.765850, -122.437094), function(err, position) {
if (err) {
$('#header').html('<p>Sorry we couldn't locate an address.</p>)
} else {
$('#header').html('<p>Your Street number is ' + street_number + '</p>');
}
});
However this says unexpected identifier in the JS console in Chrome. Any help would be appreciated. :)
I am actually the Developer Advocate # SimpleGeo. Your function displayData doesn't look like it is doing anything. Also var street_number isn't defined. Are you looking to get the user's address?
Here is an example that returns the user's neighborhood:
<script type="text/javascript">
var client = new simplegeo.ContextClient('YOUR_JSONP_TOKEN');
$(document).ready(function() {
client.getLocation({enableHighAccuracy: true}, function(err, position) {
// get the user's context for the found location
client.getContext(position.coords.latitude, position.coords.longitude,
function(err, data) {
if (err)
(typeof console == "undefined") ? alert(err) : console.error(err);
else {
for (var i = 0, ii = data.features.length; i < ii ; i++) {
// switch on the category
switch(data.features[i]["classifiers"][0]["category"]) {
// Return the Neighborhood as an example
case "Neighborhood":
$("#neighborhood").val(data.features[i]["name"]);
break;
}
}
}
});
});
});
</script>
Related
I am trying get current location with address by using Cordova geolocation plugin . but i am getting below error message.
{error_message: "You must use an API key to authenticate each reque…, please refer to http://g.co/dev/maps-no-account", results: Array(0), status: "REQUEST_DENIED"}
error_message: "You must use an API key to authenticate each request to Google Maps Platform APIs. For additional information, please refer to http://g.co/dev/maps-no-account"
results: []
status: "REQUEST_DENIED"
for getting current location. below code i am using please correct my code
$scope.init = function () {
document.addEventListener("deviceready", onDeviceReady, false);
}
function onDeviceReady() {
if (navigator.connection.type == Connection.NONE) {
} else {
}
var networkConnection = navigator.connection.type;
if (networkConnection != null) {
navigator.geolocation.getCurrentPosition(success, error);
}
else {
alert('Please check your network connection and try again.');
}
}
function success(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
getDetails(latitude, longitude);
}
function error(error) {
alert('Please check your network connection and try again.');
}
function getDetails(latitude, longitude) {
var url = "http://maps.googleapis.com/maps/api/geocode/json?latlng=" + latitude + "," + longitude + "&sensor=false";
$.getJSON(url, function (data) {
console.log(data);
});
}
Please correct my code i expected out put current location with address. Thanks for advance.
You must use an API key
When you signed up for the maps platform, you should have gotten an access key, which you need to pass with every request to authenticate.
Now, as far as i can see, you don't have that token on your URL parameters. ( You may need to send it with the request headers, check the API docs on how it expects it)
EDIT:
This is the format:
https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap
Try this:
var url = "http://maps.googleapis.com/maps/api/geocode/json?latlng=" + latitude + "," + longitude + "?key= "+"ADD YOUR KEY HERE" + "&sensor=false";
Also, try using template strings rather than having 10s of + in your string
I am writing functions in my JavaScript file to output an address. It is not the cleanest, but it worked before my current issue came up. I am trying to callback and get an address but when I log the address to the console, it is undefined. I'm not sure what I am doing wrong.
function calculateDistance(vnames, vlocations) {
// PROGRAM NEVER GOES THROUGH THIS???
clientLoc((address) => {
var origin = address;
alert("Address: " + address);
});
// PROGRAM NEVER GOES THROUGH THIS???
console.log("my location is: " + origin);
var venueNames = vnames,
venueLocs = vlocations,
service = new google.maps.DistanceMatrixService();
// 5. Output band name and distance
// Matrix settings
service.getDistanceMatrix(
{
origins: [origin],
destinations: venueLocs,
travelMode: google.maps.TravelMode.DRIVING, // Calculating driving distance
unitSystem: google.maps.UnitSystem.IMPERIAL, // Calculate distance in mi, not km
avoidHighways: false,
avoidTolls: false
},
callback
);
// Place the values into the appropriate id tags
function callback(response, status) {
// console.log(response.rows[0].elements)
// dist2 = document.getElementById("distance-result-2"),
// dist3 = document.getElementById("distance-result-3");
for(var i = 1; i < response.rows[0].elements.length + 1; i++) {
var name = document.getElementById("venue-result-" + i.toString()),
dist = document.getElementById("distance-result-" + i.toString());
// In the case of a success, assign new values to each id
if(status=="OK") {
// dist1.value = response.rows[0].elements[0].distance.text;
name.innerHTML = venueNames[i-1];
dist.innerHTML = response.rows[0].elements[i-1].distance.text;
} else {
alert("Error: " + status);
}
}
}
}
This is the function I am using the callback from:
// Find the location of the client
function clientLoc (callback) {
// Initialize variables
var lat, lng, location
// Check for Geolocation support
if (navigator.geolocation) {
console.log('Geolocation is supported!');
// Use geolocation to find the current location of the client
navigator.geolocation.getCurrentPosition(function(position) {
console.log(position);
lat = position.coords.latitude;
lng = position.coords.longitude;
// Client location coordinates (latitude and then longitude)
location = position.coords.latitude + ', ' + position.coords.longitude
// console.log(location)
// Use Axios to find the address of the coordinates
axios.get('https://maps.googleapis.com/maps/api/geocode/json?key=AIzaSyAg3DjzKVlvSvdrpm1_SU0c4c4R017OIOg', {
params: {
address: location,
key: 'AIzaSyBH6yQDUxoNA3eV81mTYREQkxPIWeZ83_w'
}
})
.then(function(response) {
// Log full response
console.log(response);
var address = response.data.results[0].formatted_address;
// Return the address
console.log(address);
//return clientLoc.address;
// CALLBACK
callback(address);
})
});
}
else {
console.log('Geolocation is not supported for this Browser/OS version yet.');
return null;
}
}
a function that has a callback doesn't block execution, so your function clientLoc gets called and presumably if that code works, the origin variable will get set and your alert call will fire ... BUT the code below clientLoc is not waiting for the clientLoc call to finish ... it proceeds through the rest of the function ... granted i'm not too familiar with the es6 syntax but the concept is the same. You probably want to move the console.log("my location is: " + origin); and any code that reiles on the origin variable being set inside the callback, to make it cleaner use some promises
It had worked previously in my code, however with the recent changes I made it seems to be broken. I tried looking online for solutions, however this seems specific to me in terms of what I need. All i want is for an "alert();" to be showen if the browser Geolocation Services request is denied. Here is the code without the alert added in. Thank you.
if (navigator.geolocation) {
// Locate position
navigator.geolocation.getCurrentPosition(displayPosition);
} else {
alert('It seems like Geolocation, which is required for this page, is not enabled in your browser. Please use a browser which supports it.');
}
blacklisted_areas = {
'area 51': [1, 2],
'pink unicorn zoo': [1, 2],
};
// Success callback function
function displayPosition(pos) {
var mylat = pos.coords.latitude;
var mylong = pos.coords.longitude;
var thediv = document.getElementById('locationinfo');
thediv.innerHTML = '<p>Your longitude is :' + mylong + ' and your latitide is ' + mylat + '</p>';
var blacklisted = false;
for (let x of Object.values(blacklisted_areas)) {
if (mylat === x[0] && mylong === x[1]) {
blacklisted = true;
}
}
if(!blacklisted){
window.location="insertURLHere";
}
}
Just handle error case:
navigator.geolocation.getCurrentPosition(displayPosition, onError);
function onError (error) {
if (error.code == error.PERMISSION_DENIED)
alert("you denied geolocation");
};
Pass a callback for on error.
if (navigator.geolocation) {
// Get user's geo position.
navigator.geolocation.getCurrentPosition(function success(position) {
// Success
}, function error(err) {
// Geolcoation denied.
if (err.code === err.PERMISSION_DENIED) {
// Determine reason for error.
if (err.message.match(/secure/i)) {
console.alert('INSECURE_ORIGIN');
} else {
console.alert('INSECURE_ORIGIN');
}
}
});
}
I have the following code set up as a job in the Parse Cloud Code for my application.
Parse.Cloud.job("requestLocations", function (request, response) {Parse.Cloud.httpRequest({
url: 'https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=29.7030428,-98.1364808&radius=900&types=restaurant&key=AIzaSyCTg0x68Q6lrCAo6-A37zkxge81jDEKpvo'
}).then(function (httpResponse) {
// Success
response.success("Success");
var parsedData = JSON.parse(httpResponse.text);
var Location = Parse.Object.extend("Locations");
for (var i = 0; i < parsedData.results.length; i++) {
var restaurant = new Location();
var placeId = parsedData.results[i].place_id;
var name = parsedData.results[i].name;
var vicinity = parsedData.results[i].vicinity;
var point = new Parse.GeoPoint({
latitude: parsedData.results[i].geometry.location.lat,
longitude: parsedData.results[i].geometry.location.lng
});
restaurant.set("placeId", placeId);
restaurant.set("name", name);
restaurant.set("vicinity", vicinity);
restaurant.set("location", point);
restaurant.save(null, {
success: function (location) {
console.log("Object ID: " + location.id);
},
error: function (location, error) {
console.log("Failed to create object, with error code: " + error.message);
}
});
}
}, function (httpResponse) {
// Error
response.error('request failed with response code ' + httpResponse)
});});
As you can see, this HTTP request should return a total of 14 places. Unfortunately, it will only return 9 places and it would also seem that which 9 are return can change. I am assuming there is a problem with the way my function is put together. Can anyone help me remedy this issue. I would like to return as many places as I want based on the radius of the HTTP request.
Thank You
The http request is done right, with a promise that's fulfilled when the request is complete. But your then() block tries to create several objects in a loop, not waiting for them all to finish, and failing to call response.success. Fix it like this...
// break it into understandable chunks, too, so, here's a function
// to build a Locations object from the http data
function locationFromResult(result) {
var Location = Parse.Object.extend("Locations");
var restaurant = new Location();
var placeId = result.place_id;
var name = result.name;
var vicinity = result.vicinity;
var point = new Parse.GeoPoint({
latitude: result.geometry.location.lat,
longitude: result.geometry.location.lng
});
restaurant.set("placeId", placeId);
restaurant.set("name", name);
restaurant.set("vicinity", vicinity);
restaurant.set("location", point);
return restaurant;
}
Parse.Cloud.job("requestLocations", function (request, response) {
var url = 'https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=29.7030428,-98.1364808&radius=900&types=restaurant&key=AIzaSyCTg0x68Q6lrCAo6-A37zkxge81jDEKpvo';
Parse.Cloud.httpRequest({url: url}).then(function (httpResponse) {
var parsedData = JSON.parse(httpResponse.text);
var locations = parsedData.results.map(function(result) {
return locationFromResult(result);
});
// this is important, saveAll of the new objects before returning
// this can also be accomplished by saving the objects individually and using Parse.Promise.when()
return Parse.Object.saveAll(locations);
}).then(function(result) {
response.success(JSON.stringify(result));
}, function(error) {
response.error(JSON.stringify(error));
});
});
I have an application in windows phone and make registration with facebook and I store some data in a table, however, a single user it is being stored more than once in the table. I tried (getting the fb-id) check on the table if a record with that fb-id, but before re registrare l new user should check whether there is, however, such as asynchronous methods there is no order and always first executes the query insertion, as I can resolve this?
client side (limited)
await App.MobileService.LoginAsync(MobileServiceAuthenticationProvider.Facebook);
Message = string.Format("User Authenticate - {0}", App.MobileService.CurrentUser.UserId);
//***** Get fb info
var userId = App.MobileService.CurrentUser.UserId;
var facebookId = userId.Substring(userId.IndexOf(':') + 1);
var client = new HttpClient();
var fbUser = await client.GetAsync("https://graph.facebook.com/" + facebookId);
var response = await fbUser.Content.ReadAsStringAsync();
var jo = JObject.Parse(response);
var FbidUser = jo.GetValue("id");
var userName = jo.GetValue("name");
var genero = jo.GetValue("gender");
but, i slould be do at server client, but how to insert info data one time, i mean, Check the record in the table before inserting.
Server side Azure:
function insert(item, user, request)
{
item.UserName = "<unknown>"; // default
var identities = user.getIdentities();
var req = require('request');
if (identities.facebook)
{
var fbAccessToken = identities.facebook.accessToken;
var url = 'https://graph.facebook.com/me?access_token=' + fbAccessToken;
req(url, function (err, resp, body)
{
if (err || resp.statusCode !== 200)
{
console.error('Error sending data to FB Graph API: ', err);
request.respond(statusCodes.INTERNAL_SERVER_ERROR, body);
}
else
{
try
{
var userData = JSON.parse(body);
item.UserName = userData.name;
request.execute();
} catch (ex)
{
console.error('Error parsing response from FB Graph API: ', ex);
request.respond(statusCodes.INTERNAL_SERVER_ERROR, ex);
}
}
});
}
}
according to the above code, i have a second question, in the developer center on facebook, I have access to email and photos (my application), I guess userData variable contains this information?, how do I access it?, how to call those properties where the rest of the information?
If all you want is to prevent two items for users with the same name to be inserted, the easiest way would be to not use the name at all, but instead use the FB id (after all, it's possible that two different people have the same name). That you can do with the script below:
function insert(item, user, request)
{
item.UserId = user.userId;
var currentTable = tables.current;
currentTable.where({ UserId: user.userId }).read({
success: function(results) {
if (results.length > 0) {
// an item with that user id already exists in the table
request.respond(400,
{ error: 'item already in the table' });
} else {
// new user, can insert it here
request.execute();
}
}
});
}
Now, if you really want to use the user name as the "key" for your table, you can do something similar as well:
function insert(item, user, request)
{
item.UserName = "<unknown>"; // default
var identities = user.getIdentities();
var req = require('request');
var currentTable = tables.current;
if (identities.facebook)
{
var fbAccessToken = identities.facebook.accessToken;
var url = 'https://graph.facebook.com/me?access_token=' + fbAccessToken;
req(url, function (err, resp, body)
{
if (err || resp.statusCode !== 200)
{
console.error('Error sending data to FB Graph API: ', err);
request.respond(statusCodes.INTERNAL_SERVER_ERROR, body);
} else {
try {
var userData = JSON.parse(body);
item.UserName = userData.name;
currentTable.where({ UserName: item.UserName }).read({
success: function(results) {
if (results.length > 0) {
request.respond(statusCodes.BAD_REQUEST,
{ error: 'Name already in the table' });
} else {
request.execute();
}
}
});
} catch (ex) {
console.error('Error parsing response from FB Graph API: ', ex);
request.respond(statusCodes.INTERNAL_SERVER_ERROR, ex);
}
}
});
}
}