Google map sync geocode delay

前端 未结 2 1089
清酒与你
清酒与你 2021-01-29 06:53

Here is it, jsfiddle

As you can see, I intend to make separate functions for google map features. The locate_self() function is used to return latlng coordi

相关标签:
2条回答
  • 2021-01-29 07:25

    The geolocation service is asynchronous. The simplest way around this is to use a callback instead of using return:

    function initialize_map(result) {
      if (result !== 'error') {
        gm_map = new google.maps.Map(gm_map_container, gm_map_options);
        if (!result) {
          result = new google.maps.LatLng(-34.397, 150.644);
        }
        gm_map.setCenter(result);
      }
    }
    
    function locate_self(callback) {
      if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function (position) {
          var pos = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
          callback(pos);
        });
      } else { callback('error'); }
    }
    
    locate_self(initialize_map);
    

    Demo.

    0 讨论(0)
  • 2021-01-29 07:50

    Why not do it the other way around?

    1. Display the map
    2. Geolocate user and set center

    http://jsfiddle.net/upsidown/rMxNL/2/

    var gm_map_container = document.getElementById('container');
    var gm_map_options = { zoom: 8 };
    
    function initialize_map(location) {
        gm_map = new google.maps.Map(gm_map_container,gm_map_options);
        if (!location) { location = new google.maps.LatLng(-34.397, 150.644); }
        gm_map.setCenter(location);
    
        locate_self();
    }
    
    function locate_self() {
        if(navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(function(position) {
    
                var pos = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
                gm_map.setCenter(pos);
            });
        } else { return false; }
    }
    
    initialize_map();
    
    0 讨论(0)
提交回复
热议问题