簡體   English   中英

如何使用Google Maps API在node.js中單擊按鈕獲得用戶輸入?

[英]How to get user input on click of button in node.js using google maps api?

我有一張地圖,使用Google Maps Geolocation api在用戶的當前位置上放置了一個標記。 但我也希望用戶能夠搜索名稱,並使應用程序在適合用戶輸入的最接近位置的第一個結果處返回另一個標記(除當前位置的標記外)。 (Google Maps api返回最近位置的數組)。

這是搜索欄和提交按鈕的HTML:

<form>
<p> Enter item here:
<input name = 'location1' id = "location2"/>
</p>
<button type = 'submit' id = "submitButton" ><center> Submit</center>
</button>
</form>

這是javascript的一部分(在ejs中),其中包含地圖的功能和應該在單擊提交按鈕后獲取用戶輸入的功能(getStoreLocation):

if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(function(position) {
              pos = {
                lat: position.coords.latitude,
                lng: position.coords.longitude
              };
              var marker = new google.maps.Marker({
                position: pos,
                map: map
              });
              map.setCenter(pos);
              document.getElementById('submitButton').onclick = function() {getStoreLocation()}
}, function() {
              handleLocationError(true, infoWindow, map.getCenter());
            });

          } else {
            // Browser doesn’t support Geolocation
            handleLocationError(false, infoWindow, map.getCenter());
          }


        }
function getStoreLocation(){
              var input = document.getElementById('location2').value
              console.log(input)
              var apiKey = 'AIzaSyDUWTdknyhqy6iOYA4y8zbR6FJN_tamIaA'
              var url = `https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=${pos.lat},${pos.lng}&radius=500&keyword=${input}&key=${apiKey}`              

              fetch(url)
              .then(function(data){
                return data.json()
              })
              .then(function(json){
                console.log(json)
                var latitudeOfInput = json.results[0].geometry.location.lat
                var longitudeOfInput = json.results[0].geometry.location.lng
                var pos2 = {
                  lat: latitudeOfInput,
                  lng: longitudeOfInput
                };

                console.log(pos2)

                var marker2 = new google.maps.Marker({
                  position: pos2,
                  map: map
                });
              })
  }

但是即使輸入了名稱並按了Submit按鈕,頁面也會返回僅在當前位置帶有一個標記的地圖,而不會返回第二個標記。 有人知道如何解決此問題或我做錯了什么嗎?

該按鈕導致頁面刷新,將按鈕的類型更改為。

<button type="button">

如果那不起作用,則將button元素更改為。

<input type="button">

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM