Using google maps API, how can we set the current location as the default set location using map.setCenter function?

前端 未结 7 1419

I am writing JavaScript code using Google Maps API.

map = new google.maps.Map2(document.getElementById(\"map_canvas\"));
map.setCenter(new google.maps.LatLng         


        
7条回答
  •  眼角桃花
    2020-12-25 14:11

    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();
    

提交回复
热议问题