首页 > 解决方案 > 从输入字段设置谷歌地图从和到方向

问题描述

我有两个字段 from 和 to,我只是想在提交时在地图上显示 from 和 to。

我无法确定地图的origindestination选项。

HTML:

    <!DOCTYPE html>
<head>
    <meta charset="UTF-8">
    <title>test</title>
    <link rel="stylesheet" href="main.css">

</head>
<body>
    <div id="map"></div>
    <script>
        function myMap() {
            var mapOptions = {
                origin: new google.maps.LatLng(59.426862, 24.743414),
                destination: new google.maps.LatLng(59.438337, 24.756494),
                zoom: 10,
                mapTypeId: google.maps.MapTypeId.HYBRID
            }
        var map = new google.maps.Map(document.getElementById("map"), mapOptions);
    }
    </script>
    <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDFOR-jYbVDU9ariN9UWKhldnV8M_nbrjQ&callback=myMap"></script>

    <div id="input-container">
        <input type="text" name="from" placeholder="From" class="special">
        <input type="text" name="from" placeholder="To">
        <input type="submit">
    </div>
</body>
</html>

标签: javascripthtml

解决方案


// change form code like this 

<form>
 <div id="input-container">
        <input type="text" name="from" placeholder="From" class="special">
        <input type="text" name="to" placeholder="To">
        <input type="submit" >
 </div>
 </form>

// using jquery update your map
<script>
$( "form" ).submit(function( event ) {
  from = $( "input[name='from']" ).val();
  to   = $( "input[name='to']" ).val();

  var myOptions = {
                    origin: new google.maps.LatLng(form),
                    destination: new google.maps.LatLng(to),
                    zoom: 10,
                    mapTypeId: google.maps.MapTypeId.HYBRID
                };
    map.set(myOptions);
  event.preventDefault();
});
</script>

推荐阅读