how to mark user's current location on Primefaces Gmap?

后端 未结 2 375
一个人的身影
一个人的身影 2021-01-13 17:10

In Gmap we can mark, desired location by passing custom latitude and longitude. Is there any way to add marker to map for user\'s CURRENT LOCATION.? Is there a way to get us

相关标签:
2条回答
  • 2021-01-13 18:00

    In addition to BalusC's answer a quote from the Google Maps API documentation (Primefaces uses this API under the hood):

    Newer browsers are starting to support the W3C Geolocation standard. This standard is part of HTML5 and will likely become the de-facto standard going forward. All applications that wish to perform geolocation should support this standard.

    Some browsers use IP addresses to detect a user's location; however, As a user's IP address can only provide a rough estimate of a user's location, we don't recommend using this approach for geolocation. The W3C approach is the easiest and most fully-supported so it should be prioritized over other methods.

    Here is a short example from the given link:

    var initialLocation;
    var browserSupportFlag =  new Boolean();
    // Try W3C Geolocation (Preferred)
      if(navigator.geolocation) {
        browserSupportFlag = true;
        navigator.geolocation.getCurrentPosition(function(position) {
          initialLocation = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
          map.setCenter(initialLocation);
        }, function() {
          handleNoGeolocation(browserSupportFlag);
        });
      }
    

    Normally, the user will be prompted and asked for permission when a website tries to access location information.

    You could first try this and if it fails go on with Balusc's answer.

    0 讨论(0)
  • 2021-01-13 18:02

    You need to figure the user's IP address and then feed it to some IP geo location tool/API in order to get the geo location in latitude/longitude. Finally use this information for your Google Map.

    All JSF can do for you is giving you the user's IP address as follows:

    ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
    HttpServletRequest request = (HttpServletRequest) externalContext.getRequest();
    String ip = request.getRemoteAddr();
    // ...
    

    If you'd like to take proxies into account as well, then check X-Forwarded-For header:

    ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
    HttpServletRequest request = (HttpServletRequest) externalContext.getRequest();
    String ip = request.getRemoteAddr();
    String forwardedFor = request.getHeader("X-Forwarded-For");
    
    if (forwardedFor != null) {
        ip = forwardedFor.split("\\s*,\\s*", 2)[0];
    }
    
    // ...
    

    Which IP geo location tool/API you in turn have to use is a question which you've to answer yourself. Just feed the keywords "ip geo location" to Google to get started.

    0 讨论(0)
提交回复
热议问题