(搜索选项不起作用)Uncaught ReferenceError:google没有定义 [英] (Search option not working) Uncaught ReferenceError: google is not defined

查看:117
本文介绍了(搜索选项不起作用)Uncaught ReferenceError:google没有定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将Google Maps API应用到我的网站上。谷歌地图加载,但搜索选项似乎仍然是由于以下错误消息


未捕获的ReferenceError:google不是定义


以下行:


var searchBox = new google.maps.places.SearchBox(input);




这段代码需要纠正的是什么?

 <!DOCTYPE html> 
< html>
< head>
< meta name =viewportcontent =initial-scale = 1.0,user-scalable = no>
< meta charset =utf-8>
< title>位置搜寻框< / title>
< style>


#map {
width:100%;
height:400px;
背景颜色:#CCC;
}

html,body {
height:100%;
保证金:0;
padding:0;
}
#map {
height:100%;
}
.controls {
margin-top:10px;
border:1px透明;
border-radius:2px 0 0 2px;
box-sizing:border-box;
-moz-box-sizing:border-box;
height:32px;
概述:无;
box-shadow:0 2px 6px rgba(0,0,0,0.3);
}

#pac-input {
background-color:#fff;
font-family:Roboto;
font-size:15px;
font-weight:300;
margin-left:12px;
padding:0 11px 0 13px;
文本溢出:省略号;
width:300px;
}

#pac-input:focus {
border-color:#4d90fe;
}

.pac-container {
font-family:Roboto;
}

#type-selector {
color:#fff;
背景颜色:#4d90fe;
padding:5px 11px 0px 11px;
}

#类型选择器标签{
font-family:Roboto;
font-size:13px;
font-weight:300;
}
#target {
width:345px;
}

< / style>
< / head>
< body>
< div id =map>< / div>
< input id =pac-inputclass =controlstype =textplaceholder =Search Box>

< script>
函数initMap(){
var mapDiv = document.getElementById('map');
var map = new google.maps.Map(mapDiv,{
center:{lat:44.540,lng:-78.546},
zoom:13,
mapTypeId:google。 maps.MapTypeId.ROADMAP
});
}

//此示例使用Google Place自动完成
//功能将搜索框添加到地图。人们可以输入地理搜索。搜索框将返回一个
//选择列表,其中包含地点和预测搜索条件的混合。

//这个例子需要Places库。第一次加载API时,请包含libraries = places
//参数。例如:
//< script src =https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places>

//函数initAutocomplete(){
// var map = new google.maps.Map(document.getElementById('map'),{
// center:{ lat:-33.8688,lng:151.2195},
// zoom:13,
// mapTypeId:google.maps.MapTypeId.ROADMAP
//});

//创建搜索框并将其链接到UI元素。
var input = document.getElementById('pac-input');
var searchBox = new google.maps.places.SearchBox(input);
map.controls [google.maps.ControlPosition.TOP_LEFT] .push(input);

//将SearchBox结果偏向当前地图的视口。
map.addListener('bounds_changed',function(){
searchBox.setBounds(map.getBounds());
});

var markers = [];
//监听用户选择预测时触发的事件,并获取该地点的
//更多详细信息。
searchBox.addListener('places_changed',function(){
var places = searchBox.getPlaces();

if(places.length == 0){
返回;
}

//清除旧的标记
markers.forEach(function(marker){
marker.setMap(null);
$ b));
markers = [];

//对于每个地方,获取图标,名称和位置
var bounds = new google.maps.LatLngBounds( );
places.forEach(function(place){
var icon = {
url:place.icon,
size:new google.maps.Size(71,71) ,
origin:new google.maps.Point(0,0),
anchor:new google.maps.Point(17,34),
scaledSize:new google.maps.Size 25,25)
};

//为每个地方创建一个标记
markers.push(new google.maps.Mar ker({
map:map,
icon:icon,
title:place.name,
position:place.geometry.location
}));

if(place.geometry.viewport){
//只有地理编码具有视口。
bounds.union(place.geometry.viewport);
} else {
bounds.extend(place.geometry.location);
}
});
map.fitBounds(bounds);
});


< / script>
< script src =http://maps.googleapis.com/maps/api/js?v=3&sensor=false&callback=initMapasync defer>< / script>
< / body>
< / html>

任何帮助将不胜感激!!! strong>

解决方案

您正在异步加载API。您需要将所有依赖API的代码放在回调函数中( initMap )。



另外,你没有阅读这个评论,你不包括地方库:

  //这个例子需要Places库。第一次加载API时,请包含libraries = places 
//参数。例如:
//< script src =https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places>

概念证明小提琴



代码段:

 函数initMap(){var mapDiv = document.getElementById('map'); var map = new google.maps.Map(mapDiv,{center:{lat:44.540,lng:-78.546},zoom:13,mapTypeId:google.maps.MapTypeId.ROADMAP}); //此示例使用Google Place自动填充//功能将搜索框添加到地图。人们可以输入地理搜索。搜索框将返回包含地点和预测搜索词汇组合的//选择列表。 //这个例子需要Places库。第一次加载API时包含libraries = places //参数。例如://< script src =https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places> //函数initAutocomplete(){// var map = new google.maps.Map(document.getElementById('map'),{// center:{lat:-33.8688,lng:151.2195},// zoom:13, // mapTypeId:google.maps.MapTypeId.ROADMAP //}); //创建搜索框并将其链接到UI元素。 var input = document.getElementById('pac-input'); var searchBox = new google.maps.places.SearchBox(input); map.controls [google.maps.ControlPosition.TOP_LEFT] .push(输入); //将SearchBox结果偏向当前地图的视口。 map.addListener('bounds_changed',function(){searchBox.setBounds(map.getBounds());}); var markers = []; //当用户选择预测并检索//该地点的更多细节时,监听所触发的事件。 search.addListener('places_changed',function(){var places = searchBox.getPlaces(); if(places.length == 0){return;} //清除旧标记marker.forEach(function(marker) {marker.setMap(null);}); markers = []; //对于每个地方,获取图标,名称和位置var bounds = new google.maps.LatLngBounds(); places.forEach(function(place) {var icon = {url:place.icon,size:new google.maps.Size(71,71),origin:new google.maps.Point(0,0),anchor:new google.maps.Point(17, 34),scaledSize:new google.maps.Size(25,25)}; //为每个地方创建一个标记marker.push(new google.maps.Marker({map:map,icon:icon,title:place .name,position:place.geometry.location})); if(place.geometry.viewport){//只有地理编码具有视口bounds.union(place.geometry.viewport);} else {bounds.extend(place。几何。位置); }}); map.fitBounds(边界); }};}  

#map {width:100%; height:400px; background-color:#CCC;} html,body {height:100%;保证金:0; padding:0;}#map {height:100%;}。controls {margin-top:10px;边框:1px实心透明; border-radius:2px 0 0 2px;盒子尺寸:边框; -moz-box-sizing:border-box; height:32px;概要:无; box-shadow:0 2px 6px rgba(0,0,0,0.3);}#pac-input {background-color:#fff;字体家族:Roboto; font-size:15px; font-weight:300; margin-left:12px;填充:0 11px 0 13px;文本溢出:省略号;宽度:300px;}#pac-input:focus {border-color:#4d90fe;}。pac-container {font-family:Roboto;}#type-selector {color:#fff; background-color:#4d90fe; padding:5px 11px 0px 11px;}#type-selector label {font-family:Roboto; font-size:13px; font-weight:300;}#target {width:345px;}

< script src =&#160;< / script>< div id = map>< / div>< input id =pac-inputclass =controlstype =textplaceholder =Search Box/>


I'm trying to implement the Google Maps API onto my website. Google Maps loads, however search option still seems to be at large due to the below error message

Uncaught ReferenceError: google is not defined

on following line:

var searchBox = new google.maps.places.SearchBox(input);

What is it that needs to be corrected to get this code going ?

<!DOCTYPE html>
<html>
  <head>  
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <title>Places Searchbox</title>
    <style>


      #map {
        width: 100%;
        height: 400px;
        background-color: #CCC;
      } 

      html, body {
        height: 100%;
        margin: 0;
        padding: 0;
      }
      #map {
        height: 100%;
      }
      .controls {
        margin-top: 10px;
        border: 1px solid transparent;
        border-radius: 2px 0 0 2px;
        box-sizing: border-box;
        -moz-box-sizing: border-box;
        height: 32px;
        outline: none;
        box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
      }

      #pac-input {
        background-color: #fff;
        font-family: Roboto;
        font-size: 15px;
        font-weight: 300;
        margin-left: 12px;
        padding: 0 11px 0 13px;
        text-overflow: ellipsis;
        width: 300px;
      }

      #pac-input:focus {
        border-color: #4d90fe;
      }

      .pac-container {
        font-family: Roboto;
      }

      #type-selector {
        color: #fff;
        background-color: #4d90fe;
        padding: 5px 11px 0px 11px;
      }

      #type-selector label {
        font-family: Roboto;
        font-size: 13px;
        font-weight: 300;
      }
      #target {
        width: 345px;
      }

    </style>
  </head>
  <body>
    <div id="map"></div>
    <input id="pac-input" class="controls" type="text" placeholder="Search Box">

        <script>
            function initMap() {
            var mapDiv = document.getElementById('map');
            var map = new google.maps.Map(mapDiv, {
            center: {lat: 44.540, lng: -78.546},            
            zoom: 13, 
            mapTypeId: google.maps.MapTypeId.ROADMAP
        });
      }

      // This example adds a search box to a map, using the Google Place Autocomplete
      // feature. People can enter geographical searches. The search box will return a
      // pick list containing a mix of places and predicted search terms.

      // This example requires the Places library. Include the libraries=places
      // parameter when you first load the API. For example:
      // <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places">

      //function initAutocomplete() {
        //  var map = new google.maps.Map(document.getElementById('map'), {
        //  center: {lat: -33.8688, lng: 151.2195},
        //  zoom: 13,
        //  mapTypeId: google.maps.MapTypeId.ROADMAP
        //});

        // Create the search box and link it to the UI element.
        var input = document.getElementById('pac-input');
        var searchBox = new google.maps.places.SearchBox(input);
        map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);

        // Bias the SearchBox results towards current map's viewport.
        map.addListener('bounds_changed', function() {
          searchBox.setBounds(map.getBounds());
        });

        var markers = [];
        // Listen for the event fired when the user selects a prediction and retrieve
        // more details for that place.
        searchBox.addListener('places_changed', function() {
          var places = searchBox.getPlaces();

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

          // Clear out the old markers.
          markers.forEach(function(marker) {
            marker.setMap(null);
          });
          markers = [];

          // For each place, get the icon, name and location.
          var bounds = new google.maps.LatLngBounds();
          places.forEach(function(place) {
            var icon = {
              url: place.icon,
              size: new google.maps.Size(71, 71),
              origin: new google.maps.Point(0, 0),
              anchor: new google.maps.Point(17, 34),
              scaledSize: new google.maps.Size(25, 25)
            };

            // Create a marker for each place.
            markers.push(new google.maps.Marker({
              map: map,
              icon: icon,
              title: place.name,
              position: place.geometry.location
            }));

            if (place.geometry.viewport) {
              // Only geocodes have viewport.
              bounds.union(place.geometry.viewport);
            } else {
              bounds.extend(place.geometry.location);
            }
          });
          map.fitBounds(bounds);
        });


    </script>   
        <script src="http://maps.googleapis.com/maps/api/js?v=3&sensor=false&callback=initMap" async defer></script>                     
  </body>
</html>

Any help would be highly appreciated !!!

解决方案

You are asynchronously loading the API. You need to put all the code that depends on the API in the callback function (initMap).

Also, you didn't read this comment, you aren't including the places library:

// This example requires the Places library. Include the libraries=places
// parameter when you first load the API. For example:
// <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places">

proof of concept fiddle

code snippet:

function initMap() {
  var mapDiv = document.getElementById('map');
  var map = new google.maps.Map(mapDiv, {
    center: {
      lat: 44.540,
      lng: -78.546
    },
    zoom: 13,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  });

  // This example adds a search box to a map, using the Google Place Autocomplete
  // feature. People can enter geographical searches. The search box will return a
  // pick list containing a mix of places and predicted search terms.

  // This example requires the Places library. Include the libraries=places
  // parameter when you first load the API. For example:
  // <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places">
  //function initAutocomplete() {
  //  var map = new google.maps.Map(document.getElementById('map'), {
  //  center: {lat: -33.8688, lng: 151.2195},
  //  zoom: 13,
  //  mapTypeId: google.maps.MapTypeId.ROADMAP
  //});

  // Create the search box and link it to the UI element.
  var input = document.getElementById('pac-input');
  var searchBox = new google.maps.places.SearchBox(input);
  map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);

  // Bias the SearchBox results towards current map's viewport.
  map.addListener('bounds_changed', function() {
    searchBox.setBounds(map.getBounds());
  });

  var markers = [];
  // Listen for the event fired when the user selects a prediction and retrieve
  // more details for that place.
  searchBox.addListener('places_changed', function() {
    var places = searchBox.getPlaces();

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

    // Clear out the old markers.
    markers.forEach(function(marker) {
      marker.setMap(null);
    });
    markers = [];

    // For each place, get the icon, name and location.
    var bounds = new google.maps.LatLngBounds();
    places.forEach(function(place) {
      var icon = {
        url: place.icon,
        size: new google.maps.Size(71, 71),
        origin: new google.maps.Point(0, 0),
        anchor: new google.maps.Point(17, 34),
        scaledSize: new google.maps.Size(25, 25)
      };

      // Create a marker for each place.
      markers.push(new google.maps.Marker({
        map: map,
        icon: icon,
        title: place.name,
        position: place.geometry.location
      }));

      if (place.geometry.viewport) {
        // Only geocodes have viewport.
        bounds.union(place.geometry.viewport);
      } else {
        bounds.extend(place.geometry.location);
      }
    });
    map.fitBounds(bounds);
  });
}

#map {
  width: 100%;
  height: 400px;
  background-color: #CCC;
}
html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
}
#map {
  height: 100%;
}
.controls {
  margin-top: 10px;
  border: 1px solid transparent;
  border-radius: 2px 0 0 2px;
  box-sizing: border-box;
  -moz-box-sizing: border-box;
  height: 32px;
  outline: none;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
}
#pac-input {
  background-color: #fff;
  font-family: Roboto;
  font-size: 15px;
  font-weight: 300;
  margin-left: 12px;
  padding: 0 11px 0 13px;
  text-overflow: ellipsis;
  width: 300px;
}
#pac-input:focus {
  border-color: #4d90fe;
}
.pac-container {
  font-family: Roboto;
}
#type-selector {
  color: #fff;
  background-color: #4d90fe;
  padding: 5px 11px 0px 11px;
}
#type-selector label {
  font-family: Roboto;
  font-size: 13px;
  font-weight: 300;
}
#target {
  width: 345px;
}

<script src="http://maps.googleapis.com/maps/api/js?v=3&libraries=places&callback=initMap" async defer></script>
<div id="map"></div>
<input id="pac-input" class="controls" type="text" placeholder="Search Box" />

这篇关于(搜索选项不起作用)Uncaught ReferenceError:google没有定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆