Google 未使用 Google 地图 API 定义

Google is not defined with Google Maps API

我在我的一个项目中使用 Google 地图 API。

地图工作正常,但有时,以完全随机的方式,地图无法加载,我收到错误消息:

Google is not defined

我尝试更改脚本位置并添加 async/defer 标记,但仍然无效。

错误是行:

map = new google.maps.Map(document.getElementById('map'), {

可能是什么问题?

更新:这里是最小版本,有时,重新加载页面,脚本不起作用,大部分时间都有效:

<script>

    function initAutocompleteSearch() {
        // Create the search box and link it to the UI element.
        const input = document.getElementById("pac-input");
        const searchBox = new google.maps.places.SearchBox(input);

        // Listen for the event fired when the user selects a prediction and retrieve
        // more details for that place.
        searchBox.addListener("places_changed", () => {
            const places = searchBox.getPlaces();

            if (places.length == 0) {
                return;
            }

            places.forEach((place) => {
                // Create a marker for each place.
                var coordinate = place.geometry.location;

                document.getElementById('pac-input-all').value = coordinate;

                var coordinate2 = document.getElementById('pac-input-all').value;
                coordinate2 = coordinate2.replace("(", "");
                coordinate2 = coordinate2.replace(")", "");
                var coordinate2_split = coordinate2.split(", ");
                var coordinate2_lat = coordinate2_split[0];
                document.getElementById('pac-input-lat').value = coordinate2_lat;
                var coordinate2_lng = coordinate2_split[1];
                document.getElementById('pac-input-lng').value = coordinate2_lng;
            });
        });
    }

</script>

<script
    src="https://maps.googleapis.com/maps/api/js?key=MYAPI&callback=initAutocompleteSearch&libraries=places&v=weekly"
    async
></script>



<div class="row">
    <div class="col-12">
        <div class="kt-portlet kt-portlet--mobile">
            <div class="kt-portlet__body">
                <div class="row">
                    <div class="col-md-12">
                        <div class="form-group">
                            <div style="height:600px; width:100%" id="map"><div align="center"></div></div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>

    var lat_prov = 41.888145;
    var lng_prov = 12.477555;

    var map;
    var prev_infowindow = false; //CLOSE OTHER
    var geocoder; //CENTER MAP
    var nameArrCont; //CENTER MAP
    var nameArr;

    function geolocation() {
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(draw_map, draw_map);

        } else {

        }

    }

    function draw_map(position) {
        if (position.code == "1" || position.code == "2") {
            lat_prov = 41.888145;
            lng_prov = 12.477555;
        } else {
            lat_prov = position.coords.latitude;
            lng_prov = position.coords.longitude;
        }
        initMap();
    }

    function initMap() {
        map = new google.maps.Map(document.getElementById('map'), {
            zoom: 16,
            minZoom: 8,
            maxZoom: 19,
            center: {lat: lat_prov, lng: lng_prov},
//            mapTypeControl: false,
//            draggable: true,
//            zoomControl: false,
//            scrollwheel: false,
//            disableDoubleClickZoom: true
        });

        var get_lat = "";
        var get_lng = "";
        if (get_lat != "" && get_lng != "") {
            var latLng = new google.maps.LatLng(get_lat, get_lng);
            map.setCenter(latLng);
        }
    }

    geolocation();

</script>

<script>

    function geocodeLatLng(geocoder) {
        const input = document.getElementById("latlng").value;
        const latlngStr = input.split(",", 2);
        const latlng = {
            lat: parseFloat(latlngStr[0]),
            lng: parseFloat(latlngStr[1]),
        };

        geocoder
                .geocode({location: latlng})
                .then((response) => {
                    if (response.results[0]) {
                        document.getElementById("address").value = response.results[0].formatted_address;
                        document.getElementById("submit").click();
                    } else {
                        //window.alert("No results found");
                    }
                })
                .catch((e) => window.alert("Geocoder failed due to: " + e));
    }

</script>

您的问题是时间问题。您正在调用 geolocation 内联,它 运行 在页面加载时调用 initMap,并且可能会在 Google 地图 API 加载之前调用 initMap

将该调用移至 initAutocomplete 函数,即 Google 地图 API 回调函数,运行 直到 API 有完成加载。

更新的代码片段:

<script>
  function initAutocompleteSearch() {
    geolocation();
    // Create the search box and link it to the UI element.
    const input = document.getElementById("pac-input");
    const searchBox = new google.maps.places.SearchBox(input);

    // Listen for the event fired when the user selects a prediction and retrieve
    // more details for that place.
    searchBox.addListener("places_changed", () => {
      const places = searchBox.getPlaces();

      if (places.length == 0) {
        return;
      }

      places.forEach((place) => {
        // Create a marker for each place.
        var coordinate = place.geometry.location;

        document.getElementById('pac-input-all').value = coordinate;

        var coordinate2 = document.getElementById('pac-input-all').value;
        coordinate2 = coordinate2.replace("(", "");
        coordinate2 = coordinate2.replace(")", "");
        var coordinate2_split = coordinate2.split(", ");
        var coordinate2_lat = coordinate2_split[0];
        document.getElementById('pac-input-lat').value = coordinate2_lat;
        var coordinate2_lng = coordinate2_split[1];
        document.getElementById('pac-input-lng').value = coordinate2_lng;
      });
    });
  }
</script>

<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initAutocompleteSearch&libraries=places&v=weekly" async></script>



<div class="row">
  <div class="col-12">
    <div class="kt-portlet kt-portlet--mobile">
      <div class="kt-portlet__body">
        <div class="row">
          <div class="col-md-12">
            <div class="form-group">
              <div style="height:600px; width:100%" id="map">
                <div align="center"></div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>

<script>
  var lat_prov = 41.888145;
  var lng_prov = 12.477555;

  var map;
  var prev_infowindow = false; //CLOSE OTHER
  var geocoder; //CENTER MAP
  var nameArrCont; //CENTER MAP
  var nameArr;

  function geolocation() {
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(draw_map, draw_map);

    } else {

    }

  }

  function draw_map(position) {
    if (position.code == "1" || position.code == "2") {
      lat_prov = 41.888145;
      lng_prov = 12.477555;
    } else {
      lat_prov = position.coords.latitude;
      lng_prov = position.coords.longitude;
    }
    initMap();
  }

  function initMap() {
    map = new google.maps.Map(document.getElementById('map'), {
      zoom: 16,
      minZoom: 8,
      maxZoom: 19,
      center: {
        lat: lat_prov,
        lng: lng_prov
      },
    });

    var get_lat = "";
    var get_lng = "";
    if (get_lat != "" && get_lng != "") {
      var latLng = new google.maps.LatLng(get_lat, get_lng);
      map.setCenter(latLng);
    }
  }

  
</script>

<script>
  function geocodeLatLng(geocoder) {
    const input = document.getElementById("latlng").value;
    const latlngStr = input.split(",", 2);
    const latlng = {
      lat: parseFloat(latlngStr[0]),
      lng: parseFloat(latlngStr[1]),
    };

    geocoder
      .geocode({
        location: latlng
      })
      .then((response) => {
        if (response.results[0]) {
          document.getElementById("address").value = response.results[0].formatted_address;
          document.getElementById("submit").click();
        } else {
          //window.alert("No results found");
        }
      })
      .catch((e) => window.alert("Geocoder failed due to: " + e));
  }
</script>