I am writing JavaScript code using Google Maps API.
map = new google.maps.Map2(document.getElementById(\"map_canvas\"));
map.setCenter(new google.maps.LatLng
This solution tries to get user location from browser first, if the user refused or any other error occurs it then gets the location from user's IP address
mapUserLocation = () => {
navigator.geolocation
? navigator.geolocation.getCurrentPosition(
handlePosition,
getLocationFromIP
)
: getLocationFromIP();
};
getLocationFromIP = () => {
fetch("http://ip-api.com/json")
.then(response => response.json())
.then(data => {
data.lat &&
data.lon &&
updateUserPosition({
lat: data.lat,
lng: data.lon
});
})
.catch(error => {
console.log(`Request failed: `, error);
});
};
handlePosition = position => {
const userPos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
updateUserPosition(userPos);
};
updateUserPosition = position => {
map.setCenter(position, 13);
};
and call it like:
mapUserLocation();