Skip to content

Commit 2d9a29d

Browse files
authored
Update Fill Address sample to new autocomplete API
1 parent f576978 commit 2d9a29d

2 files changed

Lines changed: 171 additions & 0 deletions

File tree

Lines changed: 171 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,171 @@
1+
<!DOCTYPE html>
2+
<html lang="en">
3+
<head>
4+
<title>Fill Address Form with Autocomplete - Azure Maps Web SDK Samples</title>
5+
6+
<meta charset="utf-8" />
7+
<link rel="shortcut icon" href="/favicon.ico"/>
8+
9+
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
10+
<meta name="description" content="This sample shows how to use the Azure Maps Search service with JQuery UI's autocomplete widget which provides address suggestions as the user types and which populates a form with the selected suggestion." />
11+
<meta name="keywords" content="Microsoft maps, map, gis, API, SDK, search, geocoding, geocode, autocomplete, autosuggest, jquery" />
12+
<meta name="author" content="Microsoft Azure Maps" /><meta name="version" content="1.0" />
13+
<meta name="screenshot" content="screenshot.jpg" />
14+
15+
<!-- Load JQuery UI -->
16+
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css">
17+
18+
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
19+
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
20+
21+
<!-- Add references to the Azure Maps Map control JavaScript and CSS files. -->
22+
<link href="https://atlas.microsoft.com/sdk/javascript/mapcontrol/3/atlas.min.css" rel="stylesheet" />
23+
<script src="https://atlas.microsoft.com/sdk/javascript/mapcontrol/3/atlas.min.js"></script>
24+
25+
<script>
26+
//Your Azure Maps SAS token service URL for authenticating the service.
27+
var tokenServiceUrl = 'https://samples.azuremaps.com/api/GetAzureMapsSasToken';
28+
29+
var token;
30+
31+
var addressGeocodeServiceUrlTemplate = 'https://atlas.microsoft.com/geocode:autocomplete?api-version=2025-06-01-preview&query={query}&coordinates={coordinates}&language={language}&countrySet={countrySet}';
32+
33+
async function PageLoaded() {
34+
//Retrieve a SAS token if there isn't one currently available.
35+
if (!token) {
36+
await initSasToken();
37+
}
38+
39+
//Create a jQuery autocomplete UI widget.
40+
$("#searchBox").autocomplete({
41+
minLength: 3, //Don't ask for suggestions until at least 3 characters have been typed. This will reduce costs by not making requests that will likely not have much relevance.
42+
source: function (request, response) {
43+
44+
//Create a URL to the Azure Maps search service to perform the address search.
45+
var requestUrl = addressGeocodeServiceUrlTemplate.replace('{query}', encodeURIComponent(request.term))
46+
.replace('{coordinates}', '-95.712891,37.09024') // Default set to US center coordinates
47+
.replace('{language}', 'en-US')
48+
.replace('{countrySet}', 'US'); //A comma-separated string of country codes to limit the suggestions to.
49+
50+
//Process the request.
51+
fetch(requestUrl, {
52+
method: 'GET',
53+
mode: 'cors',
54+
headers: {
55+
'Authorization': 'jwt-sas ' + token,
56+
'Content-Type': 'application/json; charset=utf-8',
57+
'Accept-Language': 'en-US'
58+
}
59+
}).then(r => r.json()).then(data => {
60+
// New API returns features array instead of results
61+
// Filter for Address type items only
62+
var results = data.features ? data.features.filter(item =>
63+
item.properties && item.properties.typeGroup === "Address"
64+
) : [];
65+
response(results);
66+
});
67+
},
68+
select: function (event, ui) {
69+
//When a suggestion has been selected.
70+
var selection = ui.item;
71+
var address = selection.properties.address;
72+
73+
//Populate the address textbox values - mapping new API structure to old fields
74+
document.getElementById('addressLineTbx').value = address.addressLine ||
75+
((address.streetNumber ? (address.streetNumber + ' ') : '') + (address.streetName || ''));
76+
document.getElementById('cityTbx').value = address.locality || '';
77+
document.getElementById('countyTbx').value = address.adminDistricts && address.adminDistricts[1] ? address.adminDistricts[1].name : '';
78+
document.getElementById('stateTbx').value = address.adminDistricts && address.adminDistricts[0] ? address.adminDistricts[0].name : '';
79+
document.getElementById('postalCodeTbx').value = address.postalCode || '';
80+
document.getElementById('countryTbx').value = address.countryRegion ? address.countryRegion.ISO : '';
81+
}
82+
}).autocomplete("instance")._renderItem = function (ul, item) {
83+
//Format the displayed suggestion to show the formatted suggestion string.
84+
var address = item.properties.address;
85+
var suggestionLabel = address.formattedAddress || address.addressLine || '';
86+
87+
if (item.properties.name) {
88+
suggestionLabel = item.properties.name + ' (' + suggestionLabel + ')';
89+
}
90+
91+
return $("<li>")
92+
.append("<a>" + suggestionLabel + "</a>")
93+
.appendTo(ul);
94+
};
95+
}
96+
97+
function getExpiration(jwtToken) {
98+
// Decode the JWT token to get the expiration timestamp
99+
const json = atob(jwtToken.split(".")[1]);
100+
const decode = JSON.parse(json);
101+
102+
// Return the milliseconds until the token needs renewed
103+
// Reduce the time until renew by 2 minutes to avoid using an expired token
104+
// The exp property is the timestamp of the expiration in seconds
105+
const renewSkew = 120000;
106+
return (1000 * decode.exp) - Date.now() - renewSkew;
107+
}
108+
109+
async function initSasToken() {
110+
//Get Azure Maps SAS token.
111+
token = await getSasToken();
112+
113+
// Create a repeating timeout that will renew the SAS token
114+
// This timeout must be cleared once the TokenCredential object is no longer needed
115+
// If the timeout is not cleared the memory used by the TokenCredential will never be reclaimed.
116+
const renewToken = async () => {
117+
try {
118+
console.log("Renewing token");
119+
token = await getSasToken();
120+
tokenRenewalTimer = setTimeout(renewToken, getExpiration(token));
121+
} catch (error) {
122+
console.log("Caught error when renewing token");
123+
clearTimeout(tokenRenewalTimer);
124+
throw error;
125+
}
126+
}
127+
tokenRenewalTimer = setTimeout(renewToken, getExpiration(token));
128+
}
129+
130+
async function getSasToken() {
131+
//Fetch a SAS token from the token service.
132+
const response = await fetch(tokenServiceUrl);
133+
return await response.text();
134+
}
135+
</script>
136+
<style>
137+
#searchBox {
138+
width: 400px;
139+
}
140+
141+
.addressForm {
142+
margin-top: 10px;
143+
background-color: #008272;
144+
color: #fff;
145+
border-radius: 10px;
146+
padding: 10px;
147+
}
148+
149+
.addressForm input {
150+
width: 265px;
151+
}
152+
</style>
153+
</head>
154+
<body onload="PageLoaded()">
155+
<input type='text' id='searchBox' />
156+
157+
<table class="addressForm">
158+
<tr><td>Street Address:</td><td><input type="text" id="addressLineTbx" /></td></tr>
159+
<tr><td>City:</td><td><input type="text" id="cityTbx" /></td></tr>
160+
<tr><td>County:</td><td><input type="text" id="countyTbx" /></td></tr>
161+
<tr><td>State:</td><td><input type="text" id="stateTbx" /></td></tr>
162+
<tr><td>Zip Code:</td><td><input type="text" id="postalCodeTbx" /></td></tr>
163+
<tr><td>Country:</td><td><input type="text" id="countryTbx" /></td></tr>
164+
</table>
165+
166+
<fieldset style="width:calc(100% - 30px);min-width:290px;margin-top:10px;">
167+
<legend>Fill Address Form with Autocomplete</legend>
168+
This sample shows how to use the Azure Maps Search service with <a href="https://jqueryui.com/autocomplete/">JQuery UI's autocomplete widget</a> which provides address suggestions as the user types and which populates a form with the selected suggestion.
169+
</fieldset>
170+
</body>
171+
</html>
20.1 KB
Loading

0 commit comments

Comments
 (0)