How to use google maps api to get user location in django? - django

I am working on a django project and need to get the user location, what I trying is either user can enter his city manually or click on locate button that will automatically finds its location and fill the city.
I tried GeoIP but it is not sufficient, is it possible with Google maps api ?
If not then how some websites automatically fills my location like - movie ticket booking, hotel booking websites ?
If you can tell me a feasible solution of what I want to achieve is ?

I used GeoLocation to get the longitude and latitude, then with google api I fetch the street-address,city, state, country, etc.
here is the code that I used -
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
let lat = position.coords.latitude;
let long = position.coords.longitude;
$("input[name='lat']").val(lat);
$("input[name='lat']").val(long);
let url_str = 'https://maps.googleapis.com/maps/api/geocode/json?latlng='+lat+','+long+'&key=yourkey'
$.getJSON(url_str, function(data) {
console.log(data);
//here you get the location data, like street address, city and pass it to inputs and submit the form to save it.
});
}

Related

Read data from Google Cloud Datastore by dialogflow agent

I am newbie in the chatbot domain. I need to develop a dialogflow chatbot which can store the data collected from user to Google Cloud Datastore Entities(not Firebase real time database) and retrieve it back when the user want to search.
I can able to write the data collected from user to datastore. But I am struggling in retrieving the data. I am writing the function in the dialogflow inline editor.
Write function :
function order_pizza(agent) {
var pizza_size = agent.parameters.size;
var pizza_topping = agent.parameters.pizza_topping;
var date_time = agent.parameters.size;
const taskKey = datastore.key('order_item');
const entity = {
key: taskKey,
data: {
item_name: 'pizza',
topping: pizza_topping,
date_time: date_time,
order_time: new Date().toLocaleString(),
size: pizza_size }
};
return datastore.save(entity).then(() => {
console.log(`Saved ${entity.key.name}: ${entity.data.item_name}`);
agent.add(`Your order for ${pizza_topping} pizza has been placed!`);
});
}
where "order_item" is the kind(table in datastore) the data is being stored. It is storing the data successfully.
Read data:(the function not working)
function search_pizza(agent){
const taskKey = datastore.key('order_item');
var orderid = agent.parameters.id;
const query = datastore.createQuery('taskKey').filter('ID','=', orderid);
return datastore.runQuery(query).then((result) =>{
agent.add(result[0]);
});
}
This is what i tried so far! Whereever i search I can find the result for firebase realtime database. But can't find solution for google datastore!
Followed many tutorial. But can't quite get it right! Kindly help!

How to get the ID of the snapshot in cloud functions?

I am using cloud functions to trig when a new document is added to the firestore but I couldn't find online how to get the ID of this document.
this is my code :
exports.sendWelcomeEmail = functions.firestore
.document(`users/{user}`)
.onCreate(async (snap, context) => {
const email = snap.data().userEmail; // The email of the user.
const displayName = snap.data().userName; // The display name of the user.
return sendWelcomeEmail(email, displayName);
});
I need to get the Id from "snap" how can I do that?
You can access particular fields as you would with any JS property, here's the link to the documentation.

Facebook Matching API - Returns empty data for any other user

I have a problem when I use the Facebook Checkbox Plugin in order to connect my users to a Facebook chatbot. When they click and the checkbox is checked, I get their user reference, and sending him/her a message, I get the user page-scoped id.
Using this user page-scoped id, I should be able to get the user app-scoped id, that I need to get more information from this user.
In order to to this, I use the facebook Matching API, and it works great for my administrator user, but as soon as I login using any other user, even if it is registered as a developer, the data that I get from the matching API is empty.
[https://developers.facebook.com/docs/messenger-platform/identity/id-matching]
Anybody has an idea about what could be happening here? My app is live (not approved), and I believe the permissions and tokens are right... If there is a problem, it should be about tokens, but I'm not sure about this.
Here, some of my code:
const accessToken = config.facebook.unlimitedPageAccessToken;
const clientSecret = config.facebook.clientSecret;
const appsecretProof = CryptoJS.HmacSHA256(accessToken, clientSecret).toString(CryptoJS.enc.Hex);
request({
url: 'https://graph.facebook.com/v2.10/'+ recipientId +'/ids_for_apps',
qs: { access_token: accessToken, appsecret_proof: appsecretProof }
}, function (error, response, body) {
if (!error && response.statusCode == 200) {
body = JSON.parse(body);
console.log("data --> " + JSON.stringify(body, null, 4));
const userAppId = body.data[0].id;
return userAppId;
} else {
console.error("Error trying to translate ID's.");
}
});
As I said, when I log in with any other user than the administrator, I get this:
{
"data": []
}
For every Facebook page, a user has a different psid. So until you get that page scoped id, you won't be able to send them a message. So may be what you can do is link the users to the page first to initialize the conversation.

How to get Display name of user profile manager property

When I was writing custom display template for SharePoint people search, I wanted to display the manager of the searched user. When I display the manager value returned from SharePoint people search, it displays as follows:
i:0#.f|membership|lpalmer#xyz.com
I want to show the display instead of the account name in my SharePoint display template. Let me know if this can be done either using JavaScript or just by doing some configurations on SharePoint user profile property change.
This cannot be done using just configurations. You will need to query the User Profile Service and get the Display Name using the login name the search service returns.
For obtaining any property you can use something like this:
function getProfilePropertyValueFromLoginName(loginName, propertyName, success, error) {
// Get the current client context and PeopleManager instance.
var clientContext = new SP.ClientContext.get_current();
var peopleManager = new SP.UserProfiles.PeopleManager(clientContext);
// Get user properties for the target user.
// To get the PersonProperties object for the current user, use the
// getMyProperties method.
var personProperties = peopleManager.getPropertiesFor(loginName);
// Load the PersonProperties object and send the request.
clientContext.load(personProperties);
clientContext.executeQueryAsync(
function () {
if (success) {
success(loginName, personProperties.get_userProfileProperties()[propertyName]);
}
}, function (sender, args) {
if (error) {
error(sender, args);
}
});
}
-Hope it helps

Retrieving Google User Photo

I am able to retrieve the thumbnailPhotoUrl from the user.list api of the google admin SDK. However, whenever I try to render the image, Google is redirecting to a static silhouette image. The URL that is retrieved via the API looks like
https://plus.google.com/_/focus/photos/private/AIbEiAIA....
As mentioned, this ends up getting redirected to:
https://ssl.gstatic.com/s2/profiles/images/silhouette200.png
However, with a little bit of reverse engineering, I can see the photo by adding /u/1/ to the beginning of the URL path, like this:
https://plus.google.com/u/1/_/focus/photos/private/AIbEiAIA...
From my research the /u/1 has something to do with multiple google accounts, so I'm afraid I wouldn't be able to rely on this method. Can anyone help me understand what's happening here?
Out of my own experience I figured out that if the thumbnailPhotoUrl has private on the URL then the photo is not public i.e. not viewable outside the domain, it could also be that the user hasn't activated their Google+ profile, which I believe makes their photo public anyway.
Best to avoid using the thumbnailPhotoUrl if the URL has a private path on it. I think it's more reliable to retrieve the photo as Web-safe base64 data using the Users.Photo API then encode it as an inline base64 CSS image.
This is the code snippet I usually use:
import com.google.common.io.BaseEncoding;
import com.google.api.services.admin.directory.model.User;
import com.google.api.services.admin.directory.model.UserPhoto;
public class PhotoUtils {
public void loadPhoto() {
// if the user have not signed up for Google+ yet then their thumbnail is private
String thumbnailUrl = user.getThumbnailPhotoUrl();
String photoData = "";
if((thumbnailUrl != null) && (thumbnailUrl.indexOf("private") > -1)) {
UserPhoto photo = getUserPhoto(user.getId());
if(photo != null) {
photoData = getBase64CssImage(photo.getPhotoData(), photo.getMimeType());
}
}
}
public static String getBase64CssImage(String urlSafeBase64Data, String mimeType) {
urlSafeBase64Data = new String(BaseEncoding.base64().encode(
BaseEncoding.base64Url().decode(urlSafeBase64Data)));
return "data:" + mimeType + ";base64," + urlSafeBase64Data;
}
public UserPhoto getUserPhoto(String userId) throws IOException {
UserPhoto photo = null;
try {
photo = this.getClient().users().photos().get(userId).execute();
} catch(GoogleJsonResponseException e) {
if(e.getMessage().indexOf(NOT_FOUND) == 0) {
log.warning("No photo is found for user: " + userId);
} else {
throw e;
}
}
return photo;
}
}
Here are my 10 cents...
Recently I've been working on building a G Suite User Picker for Angular and I ran into the same problem. Nonetheless, I kept testing and researching and in one of my tests I decided to call the directory api users list endpoint with a NON-ADMIN user. (Head Explodes 🤯) To my surprise, google permits this type of requests, although it provides non super admin data but enough to get a private thumbnail url for the user. At first I thought it was an unintended behaviour, some kind of bug if you will. That is when I ran into this documentation.
While user accounts can only be modified by administrators, any user on the domain can read user profiles. A non-admin user can make a users.get or users.list request with the viewType parameter equal to domain_public to retrieve a user's public profile. The scope https://www.googleapis.com/auth/admin.directory.user.readonly is ideal for this use case.
So it is an intended behaviour. That is when it hit me. The private url generated when retrieving the user data is intended to be used only by the requesting user. If you provide the url to other user, it will redirect to the anonymous silhouette.
From this I was able to conclude that if I need to retrieve a list of users and need the ability to view their photos, I need to call the directory api endpoint using the credentials of the user that needs to view the respective data. This serves my purpose with the G Suite User Picker widget I am building.