How to Extract Location Data with PnPJS

The SharePoint location field is a nice way of adding location information with the help of Bing Maps. It contains quite a bit of information about a given location. The field stores the data in JSON format so it’s simple to get the data that you need.

A location will be stored in the following format:

{
	"EntityType": "LocalBusiness",
	"LocationSource": "Bing",
	"LocationUri": "https://www.bingapis.com/api/v6/localbusinesses/YN873x128404500",
	"UniqueId": "https://www.bingapis.com/api/v6/localbusinesses/YN873x128404500",
	"DisplayName": "Microsoft",
	"Address": {
		"Street": "45 Liberty Boulevard",
		"City": "Malvern",
		"State": "PA",
		"CountryOrRegion": "US",
		"PostalCode": "19355"
	},
	"Coordinates": {
		"Latitude": 40.05588912963867,
		"Longitude": -75.52118682861328
	}
}

If you’re building a web part with React, and are using the pnpjs libraries, it’s pretty straight forward and here’s a snippet showing how you might do it.

import { sp } from '@pnp/sp';

...

sp.web.lists.getByTitle(this.props.listName)
     .items.getById(id).get().then((item: any) => {
         //parse the event location info
        const location = JSON.parse(item['Event_x0020_Location']);
                   
        console.log(location.Address.City);
        console.log(location.Address.State);

});

So once you have an item, you can assign it’s location field to a variable/const using JSON.Parse. Once you have that, you can access the data via properties. Address is available and has properties of it’s own. City, State, etc. That’s it. Pretty simple.

One thought on “How to Extract Location Data with PnPJS

Comments are closed.