[MS Bot Framework] Getting a user’s location in node.js

You can get items that user’s send to you, such as attachments, photos, contacts or location, through the entities array in the message received.

When you get a message from the user, you can check the entities array and find out if they sent you anything. Specifically for location data, you can check the ‘geo’ entity within the entities array to get the latitude and longitude of the user’s location. This uses the schema.org geocoordinate form.

Below is an example of a dialog that asks the user for their location then saves the location data to ‘userData’.

bot.dialog('/getUserLocation', [
    function (session){
        builder.Prompts.text(session, "Send me your current location.");
    },
    function (session) {
        if(session.message.entities.length != 0){
            session.userData.lat = session.message.entities[0].geo.latitude;
            session.userData.lon = session.message.entities[0].geo.longitude;
            session.endDialog();
        }else{
            session.endDialog("Sorry, I didn't get your location.");
        }
    }
]);

You might wanna do a check to see if ‘geo’ isn’t empty either 🙂

You can also send users a prompt for them to send their location through the ‘ChannelData’ * property. This varies depending on the platform the user is using the bot in. For example, in Telegram you can prompt a user to send you their location by providing them with a button that replaces the keyboard:

function (session){
    var data = { method: "sendMessage", parameters: { text: "<b>Save time by sending us your current location.</b>", parse_mode: "HTML", reply_markup: { keyboard: [ [ { text: "Share location", request_location: true } ] ] } } };
    const message = new builder.Message(session);
    message.setChannelData(data);
    session.send(message);
},

I believe it works in a similar way in C#, accessing the message to get the entities array to get the geo data etc.


* If you want to be able to take advantage of special features or concepts for a channel, you can send native metadata to that channel. The way you do this is to pass extra properties via the ‘ChannelData’ property.