javascript – 使用jQuery动态添加Google Map V3标记

前端之家收集整理的这篇文章主要介绍了javascript – 使用jQuery动态添加Google Map V3标记前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在使用 jquery和Google Maps V3 API动态添加标记到Google地图.单击按钮search_button时,将使用AJAX向服务器发送请求,该请求将返回与结果相对应的LatLng JSON数组,该数组将用于放置标记.但是在我的 Javascript Conole中,我收到错误属性< map>:map的值无效.我哪里做错了?这是我的代码

HTML标头JS:

  1. <script type="text/javascript">
  2. function initialize() {
  3. var latlng = new google.maps.LatLng(42.354183,-71.065063);
  4. var options = {
  5. zoom: 15,center: latlng,mapTypeId: google.maps.MapTypeId.ROADMAP
  6. };
  7. var map = new google.maps.Map(document.getElementById("map_canvas"),options);
  8. }
  9. </script>

jQuery的

  1. $(function() {
  2.  
  3. $("#search_button").click(function(e){
  4. e.preventDefault();
  5.  
  6.  
  7. // Place markers on map
  8. for( i = 0; i < json.length; i++) {
  9. var latLng = new google.maps.LatLng(json[i].lat,json[i].lng);
  10. var marker = new google.maps.Marker({
  11. position: latLng,map: map
  12. });
  13. }
  14.  
  15. });
  16. });
  17. });

解决方法

你应该将你的变量称为map.这就是全部,实际上我建议将所有内容移动到这样的javascript文件
  1. $(document).ready(initialize);
  2. var map;
  3.  
  4. function initialize() {
  5. var latlng = new google.maps.LatLng(42.354183,-71.065063);
  6. var options = {
  7. zoom: 15,mapTypeId: google.maps.MapTypeId.ROADMAP
  8. };
  9.  
  10. map = new google.maps.Map($('#map-canvas')[0],options);
  11.  
  12. $("#search_button").click(function(e){
  13. e.preventDefault();
  14.  
  15.  
  16. // Place markers on map
  17. for( i = 0; i < json.length; i++) {
  18. var latLng = new google.maps.LatLng(json[i].lat,map: map
  19. });
  20. }
  21.  
  22. });
  23. }

猜你在找的jQuery相关文章