地理编码两个地址并创建地图js googlemaps api v3

时间:2016-09-16 08:43:26

标签: javascript google-maps google-maps-api-3

我在渲染地图时遇到了问题。我想动态地在地图上显示两个标记。

地图正在渲染但不显示标记。

这是我的地图代码:

 <script type="text/javascript">
            // When the window has finished loading create our google map below
            google.maps.event.addDomListener(window, 'load', init);

            function init() {

                var delay = 100;
              var infowindow = new google.maps.InfoWindow();
                var mapOptions = {
                    // How zoomed in you want the map to start at (always required)
                    zoom: 11,

                    // The latitude and longitude to center the map (always required)
                    center: new google.maps.LatLng(51.507351, -0.127758), // New York

                    // How you would like to style the map.
                    // This is where you would paste any style found on Snazzy Maps.
                    styles: [{
                        "featureType": "water",
                        "elementType": "geometry",
                        "stylers": [{"color": "#e9e9e9"}, {"lightness": 17}]
                    }, {
                        "featureType": "landscape",
                        "elementType": "geometry",
                        "stylers": [{"color": "#f5f5f5"}, {"lightness": 20}]
                    }, {
                        "featureType": "road.highway",
                        "elementType": "geometry.fill",
                        "stylers": [{"color": "#ffffff"}, {"lightness": 17}]
                    }, {
                        "featureType": "road.highway",
                        "elementType": "geometry.stroke",
                        "stylers": [{"color": "#ffffff"}, {"lightness": 29}, {"weight": 0.2}]
                    }, {
                        "featureType": "road.arterial",
                        "elementType": "geometry",
                        "stylers": [{"color": "#ffffff"}, {"lightness": 18}]
                    }, {
                        "featureType": "road.local",
                        "elementType": "geometry",
                        "stylers": [{"color": "#ffffff"}, {"lightness": 16}]
                    }, {
                        "featureType": "poi",
                        "elementType": "geometry",
                        "stylers": [{"color": "#f5f5f5"}, {"lightness": 21}]
                    }, {
                        "featureType": "poi.park",
                        "elementType": "geometry",
                        "stylers": [{"color": "#dedede"}, {"lightness": 21}]
                    }, {
                        "elementType": "labels.text.stroke",
                        "stylers": [{"visibility": "on"}, {"color": "#ffffff"}, {"lightness": 16}]
                    }, {
                        "elementType": "labels.text.fill",
                        "stylers": [{"saturation": 36}, {"color": "#333333"}, {"lightness": 40}]
                    }, {
                        "elementType": "labels.icon",
                        "stylers": [{"visibility": "off"}]
                    }, {
                        "featureType": "transit",
                        "elementType": "geometry",
                        "stylers": [{"color": "#f2f2f2"}, {"lightness": 19}]
                    }, {
                        "featureType": "administrative",
                        "elementType": "geometry.fill",
                        "stylers": [{"color": "#fefefe"}, {"lightness": 20}]
                    }, {
                        "featureType": "administrative",
                        "elementType": "geometry.stroke",
                        "stylers": [{"color": "#fefefe"}, {"lightness": 17}, {"weight": 1.2}]
                    }]
                };

                // Get the HTML DOM element that will contain your map
                // We are using a div with id="map" seen below in the <body>
                var mapElement = document.getElementById('map');

                // Create the Google Map using our element and options defined above
                var map = new google.maps.Map(mapElement, mapOptions);

                var bounds = new google.maps.LatLngBounds();

                var geocoder = new google.maps.Geocoder();

                  function geocodeAddress(address, next) {
                    geocoder.geocode({address:address}, function (results,status)
                      {
                         if (status == google.maps.GeocoderStatus.OK) {
                          var p = results[0].geometry.location;
                          var lat=p.lat();
                          var lng=p.lng();
                          createMarker(address,lat,lng);
                        }
                        else {
                           if (status == google.maps.GeocoderStatus.OVER_QUERY_LIMIT) {
                            nextAddress--;
                            delay++;
                          } else {
                                        }
                        }
                        next();
                      }
                    );
                  }
                 function createMarker(add,lat,lng) {
                   var contentString = add;
                   var marker = new google.maps.Marker({
                     position: new google.maps.LatLng(lat,lng),
                     map: map,
                           });

                  google.maps.event.addListener(marker, 'click', function() {
                     infowindow.setContent(contentString);
                     infowindow.open(map,marker);
                   });

                   bounds.extend(marker.position);

                 }
                 var locations = ['London, United Kingdom', 'Liverpool, United Kingdom'];

                var nextAddress = 0;
                  function theNext() {
                    if (nextAddress < locations.length) {
                      setTimeout('geocodeAddress("'+locations[nextAddress]+'",theNext)', delay);
                      nextAddress++;
                    } else {
                      map.fitBounds(bounds);
                    }
                  }
                  theNext();

            }
    </script>

如何正确显示这些标记?非常感谢我提出错误的建议和反馈。

2 个答案:

答案 0 :(得分:1)

setTimeout('geocodeAddress("'+locations[nextAddress]+'",theN‌​ext)', delay);

geocodeAddress函数不会被执行,因为setTimeout第一个参数应该是一个函数。

尽管如此,

  setTimeout(geocodeAddress(locations[nextAddress], theN‌​ext), delay);

仍然看起来不太好,因为geocodeAddress不会以预期的延迟执行,而是setTimeout将评估它的第一个参数。尝试延迟3秒,你会看到我的意思。

答案 1 :(得分:0)

我在the posted codeUncaught ReferenceError: geocodeAddress is not defined

时出现javascript错误

您的所有代码都是init函数的本地代码。如果您使用setTimeout语法:

  

var timeoutID = window.setTimeout(code [,delay]);

     

<强>码

     

可选语法允许您包含字符串而不是函数,该函数在计时器到期时编译和执行。建议不要使用此语法,原因与使用eval()存在安全风险的原因相同。

该代码在全局上下文中执行。

proof of concept fiddle (map styling removed as not relevant to the issue)

代码段

&#13;
&#13;
google.maps.event.addDomListener(window, 'load', init);
// global variables
var nextAddress = 0;
var delay = 100;
var locations = ['London, United Kingdom', 'Liverpool, United Kingdom'];
var bounds = new google.maps.LatLngBounds();
var geocoder = new google.maps.Geocoder();
var infowindow = new google.maps.InfoWindow();
var map;

function init() {
  var mapOptions = {
    // How zoomed in you want the map to start at (always required)
    zoom: 11,
    // The latitude and longitude to center the map (always required)
    center: new google.maps.LatLng(51.507351, -0.127758), // New York
  };

  // Get the HTML DOM element that will contain your map
  // We are using a div with id="map" seen below in the <body>
  var mapElement = document.getElementById('map');
  // Create the Google Map using our element and options defined above
  map = new google.maps.Map(mapElement, mapOptions);
  theNext();
}

function createMarker(add, lat, lng) {
  var contentString = add;
  var marker = new google.maps.Marker({
    position: new google.maps.LatLng(lat, lng),
    map: map,
  });
  google.maps.event.addListener(marker, 'click', function() {
    infowindow.setContent(contentString);
    infowindow.open(map, marker);
  });
  bounds.extend(marker.position);
}

function geocodeAddress(address, next) {
  geocoder.geocode({
    address: address
  }, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
      var p = results[0].geometry.location;
      var lat = p.lat();
      var lng = p.lng();
      createMarker(address, lat, lng);
    } else {
      if (status == google.maps.GeocoderStatus.OVER_QUERY_LIMIT) {
        nextAddress--;
        delay++;
      } else {}
    }
    next();
  });
}

function theNext() {
  if (nextAddress < locations.length) {
    setTimeout('geocodeAddress("' + locations[nextAddress] + '",theNext)', delay);
    nextAddress++;
  } else {
    map.fitBounds(bounds);
  }
}
&#13;
html,
body,
#map {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}
&#13;
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map"></div>
&#13;
&#13;
&#13;