Google Maps geocoding (address to GLatLng)

后端 未结 1 1672
轻奢々
轻奢々 2021-01-06 13:17

I am trying to draw a geodesic polyline with Google Maps JavaScript API from two address points.

var polyOptions = {geodesic:true};
var pol         


        
相关标签:
1条回答
  • 2021-01-06 14:01

    You may want to check out the following example. First it tries to geocode address1. If it succeeds, it tries to geocode address2. If both succeed, it plots the geodesic polyline between the two coordinates, and two markers:

    <!DOCTYPE html>
    <html> 
    <head> 
      <meta http-equiv="content-type" content="text/html; charset=UTF-8"/> 
      <title>Google Maps API Geocoding Demo</title> 
      <script src="http://maps.google.com/maps/api/js?sensor=false" 
              type="text/javascript"></script>
    </head> 
    <body>
      <div id="map" style="width: 500px; height: 400px;"></div>
    
      <script type="text/javascript">
        var address1 = 'London, UK';
        var address2 = 'New York, US';
    
        var map = new google.maps.Map(document.getElementById('map'), {
          zoom: 2,
          center: new google.maps.LatLng(35.00, -25.00),
          mapTypeId: google.maps.MapTypeId.ROADMAP
        });
    
        var gc = new google.maps.Geocoder();
    
        gc.geocode({'address': address1}, function (res1, status) {
          if (status == google.maps.GeocoderStatus.OK) {
            gc.geocode({'address': address2}, function (res2, status) {
              if (status == google.maps.GeocoderStatus.OK) {
                new google.maps.Marker({
                  position: res1[0].geometry.location,
                  map: map
                });
    
                new google.maps.Marker({
                  position: res2[0].geometry.location,
                  map: map
                });
    
                new google.maps.Polyline({
                  path: [
                    res1[0].geometry.location,
                    res2[0].geometry.location
                  ],
                  strokeColor: '#FF0000',
                  geodesic: true,
                  map: map
                });
              }
            });
          }            
        });
    
      </script>
    </body>
    </html>
    

    Screenshot:

    Google Maps API Geocoding Demo

    0 讨论(0)
提交回复
热议问题