如何根据从下拉菜单中选择的城市显示Google地图 [英] How to display a Google Map based on City selected from a Dropdown Menu

查看:150
本文介绍了如何根据从下拉菜单中选择的城市显示Google地图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要根据所选地点显示地图。我需要知道如何根据下拉菜单更改地图。这是我迄今为止,但我似乎无法弄清楚如何使用从下拉列表中选择实际更改地图。我在这里完全消隐。任何引用或帮助非常感谢。这是我目前的代码。

I need to display a map based on a place being selected. I need to know how to change the map based on the dropdown menu. Here is what I have so far, but I cannot seem to figure out how to actually change the map using a selection from the dropdown. I am just completely blanking here. Any references or help is greatly appreciated. Here is the code I currently have.

<script>
    function myMap() {
        var mapCanvas = document.getElementById("map");
        var mapOptions = {  
        center: new google.maps.LatLng(40.685646, -76.195499), zoom: 10 
    };
    var map = new google.maps.Map(mapCanvas, mapOptions);
}

</script>

<div>
    <h2>Please Choose a City</h2>
</div>
<form>
    <fieldset>
        <label>
            Cities
        </label>
        <select id="myCity" name="myCity">
            <option value="None">Select a City</option>
            <option value="PHI">Philadelphia, PA</option>
            <option value="NYC">New York, NY</option>
            <option value="HAR">Hartford, CT</option>
        </select>
    </fieldset>
</form>


推荐答案

只需按城市钥匙存储坐标。当选择更改时,取值,获取坐标并调用方法 setCenter docs

Just store the coords by the city key. When the select change, take the value, get the coords and call the method setCenter (docs) with these coords.

让我知道是否有什么不清楚的内容。

Let me know if something is not clear.

data-console =truedata-babel =false>
var map;
function myMap() {
  var mapCanvas = document.getElementById("map");
  var mapOptions = {  
    center: new google.maps.LatLng(40.685646, -76.195499), 
    zoom: 10 
  };
  map = new google.maps.Map(mapCanvas, mapOptions);
}

myMap();

var coords = {
  'PHI': '39.953050,-75.163961',
  'NYC': '40.875597,-77.776226',
  'HAR': '41.763633,-72.682662'
};

function changeMap(city) {
  var c = coords[city].split(',');
  map.setCenter(new google.maps.LatLng(c[0], c[1]));
}

#map {
  height: 200px;
}

<script src="https://maps.googleapis.com/maps/api/js"></script>

<div>
  <h2>Please Choose a City</h2>
</div>
<form>
  <fieldset>
    <label>
      Cities
    </label>
    <select id="myCity" name="myCity" onchange="changeMap(this.value)">
      <option value="None">Select a City</option>
      <option value="PHI">Philadelphia, PA</option>
      <option value="NYC">New York, PA</option>
      <option value="HAR">Hartford, CT</option>
    </select>
  </fieldset>
</form>
<div id="map"></div>

http://output.jsbin.com/suhiveb

这篇关于如何根据从下拉菜单中选择的城市显示Google地图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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