如何添加搜索框到谷歌地图与街景

时间:2014-03-30 01:46:13

标签: javascript google-maps google-maps-api-3

我希望在搜索框中输入新地址时,地图会更新为用户提供的新地址。这是我尝试但不起作用的

    <!DOCTYPE html>
    <html>
      <head>
        <meta charset="utf-8">
        <title>Street View service</title>
        <style>
          html, body, #map-canvas {
            height: 100%;
            margin: 0px;
            padding: 0px
          }
        </style>
        <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
        <script>
        var lag =151.1956316;
        var lat = -33.8665433;
    function initialize() {
      var fenway = new google.maps.LatLng( lat, lag);
      var mapOptions = {
        center: fenway,
        zoom: 14
      };
      var map = new google.maps.Map(
          document.getElementById('map-canvas'), mapOptions);
      var panoramaOptions = {
        position: fenway,
        pov: {
          heading: 34,
          pitch: 10
        }
      };
      var panorama = new  google.maps.StreetViewPanorama(document.getElementById('pano'),panoramaOptions);
      map.setStreetView(panorama);
    }
    // search for new Addreess
    var addressField = document.getElementById('search_address');
    var geocoder = new google.maps.Geocoder();
    function search() {
        geocoder.geocode(
            {'address': addressField.value}, 
            function(results, status) { 
                if (status == google.maps.GeocoderStatus.OK) { 
                    var loc = results[0].geometry.location;
                    // use loc.lat(), loc.lng()
                    lat = loc.lat();
                    lag = loc.lng();

            google.maps.event.addDomListener(window, 'load', initialize);

                } 
                else {
                    alert("Not found: " + status); 
                } 
            }
        );
    };


    google.maps.event.addDomListener(window, 'load', initialize);
            </script>
      </head>
      <body>
        <div id="map-canvas" style="width: 400px; height: 300px"></div>
<div id="pano" style="position:absolute; left:410px; top: 8px; width: 400px; height: 300px;"></div>
        <div id="panel">
         <input type="text" id="search_address" value=""/>
         <button onclick="search();">Search</button>
        </div>
      </body>
    </html>

它尝试了很多选项,但仍无法正常工作

1 个答案:

答案 0 :(得分:0)

有两个问题:

  1. addressField - 变量定义得太早(此时输入未知)
  2. 修改滞后/纬度变量不会对地图/全景产生影响    (您必须将LatLng分配给center的{​​{1}} / map的{​​{1}}