在同一个html页面的google地图上使用initMap和initAutocomplete [英] Using initMap and initAutocomplete on same html page google maps

查看:132
本文介绍了在同一个html页面的google地图上使用initMap和initAutocomplete的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个网页,我想使用地方自动完成以及谷歌地图与标记。用户可以在自动完成的地方搜索地址。标记的纬度数据来自数据库,这不会改变。问题是地图工作或地方自动完成,但不是两个,并且问题与回调有关。



在google文档中,我将两个回调都包含在单独的API中调用:

 < script src =https://maps.googleapis.com/maps/api/js?key= [API KEY]& signed_in = true& libraries = places& callback = initAutocompleteasync defer>< / script> 
< script async defer src =https://maps.googleapis.com/maps/api/js?key=[API KEY]& callback = initMap>< / script>

但是这会在控制台上抛出错误,并且没有任何效果。



我的问题是:如何将多个回调传递给Google API?



非常感谢您的帮助。

谢谢

解决方案

你不能添加多个回调(你不应该多次包含API)。将所有代码放在一个回调中。

 < script src =https://maps.googleapis.com/maps / api / js?key = [API KEY]& signed_in = true& libraries = places& callback = initializeasync defer>< / script> 

函数initialize(){
initMap();
initAutoComplete();
}

或参阅这个例子在文档



function

initialize(){initMap(); initAutocomplete();} var map,marker;函数initMap(){map = new google.maps.Map(document.getElementById('map'),{center:{lat:-34.397,lng:150.644},zoom:8 }); } //这个例子显示了一个地址表单,使用Google Places API的自动完成功能来帮助用户填写信息.//这个例子需要Places库。第一次加载API时包含libraries = places //参数。例如://< script src =https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places> var placeSearch,autocomplete; var componentForm = {street_number:'short_name ',route:'long_name',locality:'long_name',administrative_area_level_1:'short_name',country:'long_name',postal_code:'short_name'};函数initAutocomplete(){//创建自动完成对象,将搜索限制为地理位置//位置类型。 autocomplete = new google.maps.places.Autocomplete(/ ** @type {!HTMLInputElement} * /(document.getElementById('autocomplete')),{types:['geocode']}); //当用户从下拉列表中选择一个地址时,填写表单中的地址字段。 autocomplete.addListener('place_changed',fillInAddress);}函数fillInAddress(){//从自动完成对象中获取地点详细信息。 var place = autocomplete.getPlace(); if(place.geometry.viewport){map.fitBounds(place.geometry.viewport); } else {map.setCenter(place.geometry.location); map.setZoom(17); //为什么选择17?因为它看起来不错。 } if(!marker){marker = new google.maps.Marker({map:map,anchorPoint:new google.maps.Point(0,-29)}); } else marker.setMap(null); marker.setOptions({position:place.geometry.location,map:map}); for(componentForm中的var组件){document.getElementById(component).value =''; document.getElementById(component).disabled = false; } //从地点详细信息中获取地址的每个组成部分//并填充表单上的相应字段。 for(var i = 0; i< place.address_components.length; i ++){var addressType = place.address_components [i] .types [0]; if(componentForm [addressType]){var val = place.address_components [i] [componentForm [addressType]]; document.getElementById(addressType).value = val; }}} //将自动完成对象偏移到用户的地理位置,//由浏览器的'navigator.geolocation'提供object.function geolocate(){if(navigator.geolocation){navigator.geolocation.getCurrentPosition(function(position ){var geolocation = {lat:position.coords.latitude,lng:position.coords.longitude}; var circle = new google.maps.Circle({center:geolocation,radius:position.coords.accuracy});自动完成。 setBounds(circle.getBounds());}); }}

html,body {height:100%;保证金:0; padding:0;}#map {height:100%;}#locationField,#controls {position:relative; width:480px;}#autocomplete {position:absolute; top:0px; left:0px; width:99%;}。label {text-align:right; font-weight:bold;宽度:100px;颜色:#303030;}#地址{border:1px solid#000090; background-color:#f0f0ff; width:480px; padding-right:2px;}#address td {font-size:10pt;}。field {width:99%;}。slimField {width:80px;}。widthField {width:200px;}#locationField {height:20px; margin-bottom:2px;}

< div id = locationField > < input id =autocompleteplaceholder =输入您的地址onFocus =geolocate()type =text/>< / div>< table id =address> < TR> < td class =label>街道地址< / td> < td class =slimField> < input class =fieldid =street_numberdisabled =true/> < / TD> < td class =wideFieldcolspan =2> < input class =fieldid =routedisabled =true/> < / TD> < / TR> < TR> < td class =label>城市< / td> < td class =wideFieldcolspan =3> < input class =fieldid =localitydisabled =true/> < / TD> < / TR> < TR> < td class =label>状态< / td> < td class =slimField> < input class =fieldid =administrative_area_level_1disabled =true/> < / TD> < td class =label>邮政编码< / td> < td class =wideField> < input class =fieldid =postal_codedisabled =true/> < / TD> < / TR> < TR> < td class =label>国家< / td> < td class =wideFieldcolspan =3> < input class =fieldid =countrydisabled =true/> < / TD> < / table>< div id =map>< / div>< script src =https://maps.googleapis.com/maps/api/js?libraries=places& ; callback = initializedefer>< / script>


I have a webpage where I would like to use both place autocomplete as well as google map with marker. User can search for an address in place autocomplete. Lat-long data for marker comes from DB and this doesn't change. The problem is either map works or place autocomplete, but not both, and the issue is related to callbacks.

From google docs, I've included both callbacks in separate API calls:

<script src="https://maps.googleapis.com/maps/api/js?key=[API KEY]&signed_in=true&libraries=places&callback=initAutocomplete" async defer></script>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=[API KEY]&callback=initMap"></script>

But this throws error on console, and nothing works.

My question is: How multiple callbacks can be passed to Google API?

Highly appreciate your help.

Thanks

解决方案

You can't add multiple callbacks (and you shouldn't include the API more than once). Put all the code in a single callback.

<script src="https://maps.googleapis.com/maps/api/js?key=[API KEY]&signed_in=true&libraries=places&callback=initialize" async defer></script>

function initialize() {
   initMap();
   initAutoComplete();
}

or see this example in the documentation

function initialize() {
  initMap();
  initAutocomplete();
}
var map, marker;

function initMap() {
    map = new google.maps.Map(document.getElementById('map'), {
      center: {
        lat: -34.397,
        lng: 150.644
      },
      zoom: 8
    });
  }
  // This example displays an address form, using the autocomplete feature
  // of the Google Places API to help users fill in the information.

// 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">

var placeSearch, autocomplete;
var componentForm = {
  street_number: 'short_name',
  route: 'long_name',
  locality: 'long_name',
  administrative_area_level_1: 'short_name',
  country: 'long_name',
  postal_code: 'short_name'
};

function initAutocomplete() {
  // Create the autocomplete object, restricting the search to geographical
  // location types.
  autocomplete = new google.maps.places.Autocomplete(
    /** @type {!HTMLInputElement} */
    (document.getElementById('autocomplete')), {
      types: ['geocode']
    });

  // When the user selects an address from the dropdown, populate the address
  // fields in the form.
  autocomplete.addListener('place_changed', fillInAddress);
}

function fillInAddress() {
  // Get the place details from the autocomplete object.
  var place = autocomplete.getPlace();
  if (place.geometry.viewport) {
    map.fitBounds(place.geometry.viewport);
  } else {
    map.setCenter(place.geometry.location);
    map.setZoom(17); // Why 17? Because it looks good.
  }
  if (!marker) {
    marker = new google.maps.Marker({
      map: map,
      anchorPoint: new google.maps.Point(0, -29)
    });
  } else marker.setMap(null);
  marker.setOptions({
    position: place.geometry.location,
    map: map
  });

  for (var component in componentForm) {
    document.getElementById(component).value = '';
    document.getElementById(component).disabled = false;
  }

  // Get each component of the address from the place details
  // and fill the corresponding field on the form.
  for (var i = 0; i < place.address_components.length; i++) {
    var addressType = place.address_components[i].types[0];
    if (componentForm[addressType]) {
      var val = place.address_components[i][componentForm[addressType]];
      document.getElementById(addressType).value = val;
    }
  }
}

// Bias the autocomplete object to the user's geographical location,
// as supplied by the browser's 'navigator.geolocation' object.
function geolocate() {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(position) {
      var geolocation = {
        lat: position.coords.latitude,
        lng: position.coords.longitude
      };
      var circle = new google.maps.Circle({
        center: geolocation,
        radius: position.coords.accuracy
      });
      autocomplete.setBounds(circle.getBounds());
    });
  }
}

html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
}
#map {
  height: 100%;
}
#locationField,
#controls {
  position: relative;
  width: 480px;
}
#autocomplete {
  position: absolute;
  top: 0px;
  left: 0px;
  width: 99%;
}
.label {
  text-align: right;
  font-weight: bold;
  width: 100px;
  color: #303030;
}
#address {
  border: 1px solid #000090;
  background-color: #f0f0ff;
  width: 480px;
  padding-right: 2px;
}
#address td {
  font-size: 10pt;
}
.field {
  width: 99%;
}
.slimField {
  width: 80px;
}
.wideField {
  width: 200px;
}
#locationField {
  height: 20px;
  margin-bottom: 2px;
}

<div id="locationField">
  <input id="autocomplete" placeholder="Enter your address" onFocus="geolocate()" type="text" />
</div>

<table id="address">
  <tr>
    <td class="label">Street address</td>
    <td class="slimField">
      <input class="field" id="street_number" disabled="true" />
    </td>
    <td class="wideField" colspan="2">
      <input class="field" id="route" disabled="true" />
    </td>
  </tr>
  <tr>
    <td class="label">City</td>
    <td class="wideField" colspan="3">
      <input class="field" id="locality" disabled="true" />
    </td>
  </tr>
  <tr>
    <td class="label">State</td>
    <td class="slimField">
      <input class="field" id="administrative_area_level_1" disabled="true" />
    </td>
    <td class="label">Zip code</td>
    <td class="wideField">
      <input class="field" id="postal_code" disabled="true" />
    </td>
  </tr>
  <tr>
    <td class="label">Country</td>
    <td class="wideField" colspan="3">
      <input class="field" id="country" disabled="true" />
    </td>
  </tr>
</table>
<div id="map"></div>
<script src="https://maps.googleapis.com/maps/api/js?libraries=places&callback=initialize" defer></script>

这篇关于在同一个html页面的google地图上使用initMap和initAutocomplete的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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