在加载地图和标记后,在选择框上更改Google地图位置 [英] Change google map location on selectbox change after the map and markers loaded

查看:179
本文介绍了在加载地图和标记后,在选择框上更改Google地图位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何更改Google地图位置,以便另一个纬度和长坐标位于选择框更改的Google地图的中心。地图和标记已经成功加载。唯一需要改变的地方就是在从选择框中选择已经载入的地图到正确的城市。标记坐标不应该改变。

How to change the Google map location so that another lat and long coordinates are in the center of the google map on selectbox change. The map and markers were already loaded successfully. The only thing to change is to let's say scroll the already loaded map to the proper city when it is chosen from the selectbox. The coordinates of markers should NOT be changed.

<select>
  <option value="1" selected>NYC</option>
  <option value="2">Chicago</option>
  <option value="3">Boston</option>
</select>

<div class="map-container">
    <div id="map"></div><!--the google map is loaded already-->
</div>


推荐答案

如果您有下拉列表的位置坐标城市,使用它们。如果没有,您可以使用地理编码器(如果您提供可识别的名称):

If you have the coordinates of the locations of the dropdown city, use them. If not, you can use the geocoder (if you provide names it recognizes):

代码段:

function initialize() {
  var map = new google.maps.Map(document.getElementById("map"));
  var geocoder = new google.maps.Geocoder();
  $("#dropdown").change(function() {
    address = $("#dropdown :selected")[0].text;
    geocodeAddress(address, geocoder, map);
  });
  var address = $("#dropdown :selected")[0].text;
  geocodeAddress(address, geocoder, map);
}
google.maps.event.addDomListener(window, "load", initialize);

function geocodeAddress(address, geocoder, resultsMap) {
  document.getElementById('info').innerHTML = address;
  geocoder.geocode({
    'address': address
  }, function(results, status) {
    if (status === google.maps.GeocoderStatus.OK) {
      resultsMap.fitBounds(results[0].geometry.viewport);
      document.getElementById('info').innerHTML += "<br>" + results[0].geometry.location.toUrlValue(6);
    } else {
      alert('Geocode was not successful for the following reason: ' + status);
    }
  });
}

html,
body,
#map,
.map-container {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}

<script src="https://maps.googleapis.com/maps/api/js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="dropdown">
  <option value="1" selected>New York City</option>
  <option value="2">Chicago</option>
  <option value="3">Boston</option>
  <option value="4">Palo Alto</option>
  <option value="5">Seattle</option>
</select>
<div id="info"></div>
<div class="map-container">
  <div id="map"></div>
  <!--the google map is loaded already-->
</div>

这篇关于在加载地图和标记后,在选择框上更改Google地图位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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