javascript - 谷歌地图设置位置?

标签 javascript google-maps-api-3

我有这段代码,显示“LatLng”坐标中指定的当前位置。但我想要的是有一个输入框,假设有两个输入框“位置来自”和“位置至”。我希望显示所指示的 2 个框中给定输入值的当前位置。

这在 Google map V3 中可行吗?

我想让mapOptions值成为框中输入的值。 如何做到这一点?

这是我的代码。

<!DOCTYPE html>
<html>
  <head>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
    <style type="text/css">
      html { height: 100% }
      body { height: 100%; margin: 0; padding: 0 }
      #map_canvas { height: 100% }
    </style>
    <script type="text/javascript"
      src="http://maps.googleapis.com/maps/api/js?key=AIzaSyBQ8OCC8En5vNHod25Ov3Qs5E1v7NPRSsg&sensor=true">
    </script>
    <script type="text/javascript">
      function initialize() {
                    // add mapOptions here to the values in the input boxes.
        var mapOptions = {
          center: new google.maps.LatLng(-34.397, 100.644),
          zoom: 2,
          mapTypeId: google.maps.MapTypeId.ROADMAP  
        };
        var map = new google.maps.Map(document.getElementById("map_canvas"),
            mapOptions);
      }
    </script>
  </head>
  <body>

    From: <input type="text" name="From"><br>
    To: <input type="text" name="To"><br>

    <button type="button" onclick="initialize()">View example (map-simple.html)</button>

    <div id="map_canvas" style="width:100%; height:100%"></div>
  </body>
</html>

谢谢

杰森

最佳答案

你应该使用geocoder来实现

geocoder = new google.maps.Geocoder();      
var address = document.getElementById('address').value; //input box value
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
    map.setCenter(results[0].geometry.location);
    var marker = new google.maps.Marker({
        map: map,
        position: results[0].geometry.location
    });
}
});  

Map Fiddle

关于javascript - 谷歌地图设置位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12908908/

相关文章:

javascript - 未捕获的类型错误 : Cannot read property 'route'

javascript - 标记在 Google map API 中不起作用

javascript - 阅读更多 显示额外内容

javascript - 在 Promise() 中使用 while 循环

javascript - 无法显示和更新我的位置标记

google-maps - 谷歌地图地点标签语言

ios - GMSMarker iOS 问题

javascript - 你如何在 NodeJS 模块中共享常量?

javascript - Google DFP 广告管理系统 - Safeframe - 展开广告

javascript - jQuery 插件,获取原始元素的 .data()