Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Get a reference to the player object
- var player = GetPlayer();
- // Function to handle successful geolocation
- function successCallback(position) {
- // Extract latitude and longitude from the position object, rounded to 3 decimal places
- var latitude = position.coords.latitude.toFixed(3);
- var longitude = position.coords.longitude.toFixed(3);
- // Create a string with the latitude and longitude
- var locationString = "Latitude: " + latitude + ", Longitude: " + longitude;
- // Set the location string to a variable in the player object
- player.SetVar("vUserLocation", locationString);
- // Create a new XMLHttpRequest object for making an HTTP request
- var xhr = new XMLHttpRequest();
- // Construct the URL for reverse geocoding using OpenStreetMap's Nominatim service
- var url = "https://nominatim.openstreetmap.org/reverse?format=json&lat=" + latitude + "&lon=" + longitude;
- // Open a GET request to the constructed URL
- xhr.open("GET", url, true);
- // Set up a function to handle the response from the server
- xhr.onreadystatechange = function() {
- // Check if the request is complete and successful
- if (xhr.readyState === 4 && xhr.status === 200) {
- // Parse the JSON response
- var response = JSON.parse(xhr.responseText);
- // If address information is available in the response
- if (response.address) {
- // Extract various address components, using fallbacks if certain fields are not available
- var country = response.address.country || "";
- var city = response.address.city || response.address.town || response.address.village || "";
- var postcode = response.address.postcode || "";
- var state = response.address.state || "";
- var street = response.address.road || "";
- // Set the extracted address components to variables in the player object
- player.SetVar("vCountry", country);
- player.SetVar("vCity", city);
- player.SetVar("vPostcode", postcode);
- player.SetVar("vState", state);
- player.SetVar("vStreet", street);
- }
- }
- };
- // Send the HTTP request
- xhr.send();
- }
- // Function to handle geolocation errors
- function errorCallback(error) {
- // Create an error message
- var errorMessage = "Error retrieving location: " + error.message;
- // Set the error message to a variable in the player object
- player.SetVar("vError", errorMessage);
- }
- // Check if geolocation is supported by the browser
- if (navigator.geolocation) {
- // If supported, request the current position
- navigator.geolocation.getCurrentPosition(successCallback, errorCallback);
- } else {
- // If not supported, set an error message in the player object
- player.SetVar("vError", "Geolocation is not supported by this browser.");
- }
Advertisement
Add Comment
Please, Sign In to add comment