使用 Google Maps JavaScript API v3 和 Geocoding API 映射多个位置

Posted

技术标签:

【中文标题】使用 Google Maps JavaScript API v3 和 Geocoding API 映射多个位置【英文标题】:Mapping multiple locations with Google Maps JavaScript API v3 and Geocoding API 【发布时间】:2015-06-10 08:52:56 【问题描述】:

我正在使用 Google Maps javascript API v3 生成具有多个位置/标记的地图。我只有这些位置的地址,没有坐标,所以我使用 Geocoding API 来获取坐标。

我终于让谷歌的地理编码工作了,所以位置标记出现在它们应该在的位置。但是,相同的内容显示在每个 InfoWindow 中。我似乎无法将位置数组传递给地理编码函数。 (顺便说一句,我还尝试为地理编码结果创建一个变量,并将 infoWindow 函数移动到地理编码函数之外,但我也无法做到这一点。)

我已经尝试了一百种不同的方法。我希望别人能看到我看不到的东西。

    var locations = [
        ['Location 1 Name', 'Location 1 Address', 'Location 1 URL'],
        ['Location 2 Name', 'Location 2 Address', 'Location 2 URL'],
        ['Location 3 Name', 'Location 3 Address', 'Location 3 URL']
    ];

    geocoder = new google.maps.Geocoder();

    for (i = 0; i < locations.length; i++) 

        title = locations[i][0];
        address = locations[i][1];
        url = locations[i][2];

        geocoder.geocode( 'address' : locations[i][1] , function(results, status) 
          marker = new google.maps.Marker(
              icon: 'marker_blue.png',
              map: map,
              position: results[0].geometry.location,
              title: title,
              animation: google.maps.Animation.DROP,
              address: address,
              url: url
          )
          infoWindow(marker, map, title, address, url);
        )

    

    function infoWindow(marker, map, title, address, url) 
        google.maps.event.addListener(marker, 'click', function() 
            var html = "<div><h3>" + title + "</h3><p>" + address + "<br></div><a href='" + url + "'>View location</a></p></div>";
            iw = new google.maps.InfoWindow( content : html, maxWidth : 350);
            iw.open(map,marker);
        );
    

【问题讨论】:

【参考方案1】:

这是google map info window multiple addresses via xml 的副本,但不是完全相同的副本。地理编码器是异步的,所以当地理编码器回调运行时,地址的值是所有调用的循环结束时的值。

答案是一样的:最简单的解决方案是使用函数闭包将地理编码器的调用与返回的结果相关联:

function geocodeAddress(locations, i) 
    var title = locations[i][0];
    var address = locations[i][1];
    var url = locations[i][2];
    geocoder.geocode(
        'address': locations[i][1]
    ,

    function (results, status) 
        if (status == google.maps.GeocoderStatus.OK) 
            var marker = new google.maps.Marker(
                icon: 'http://maps.google.com/mapfiles/ms/icons/blue.png',
                map: map,
                position: results[0].geometry.location,
                title: title,
                animation: google.maps.Animation.DROP,
                address: address,
                url: url
            )
            infoWindow(marker, map, title, address, url);
            bounds.extend(marker.getPosition());
            map.fitBounds(bounds);
         else 
            alert("geocode of " + address + " failed:" + status);
        
    );

Working fiddle

代码sn-p:

var locations = [
  ['Location 1 Name', 'New York, NY', 'Location 1 URL'],
  ['Location 2 Name', 'Newark, NJ', 'Location 2 URL'],
  ['Location 3 Name', 'Philadelphia, PA', 'Location 3 URL']
];

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

function initialize() 
  map = new google.maps.Map(
    document.getElementById("map_canvas"), 
      center: new google.maps.LatLng(37.4419, -122.1419),
      zoom: 13,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    );
  geocoder = new google.maps.Geocoder();

  for (i = 0; i < locations.length; i++) 


    geocodeAddress(locations, i);
  

google.maps.event.addDomListener(window, "load", initialize);

function geocodeAddress(locations, i) 
  var title = locations[i][0];
  var address = locations[i][1];
  var url = locations[i][2];
  geocoder.geocode(
      'address': locations[i][1]
    ,

    function(results, status) 
      if (status == google.maps.GeocoderStatus.OK) 
        var marker = new google.maps.Marker(
          icon: 'http://maps.google.com/mapfiles/ms/icons/blue.png',
          map: map,
          position: results[0].geometry.location,
          title: title,
          animation: google.maps.Animation.DROP,
          address: address,
          url: url
        )
        infoWindow(marker, map, title, address, url);
        bounds.extend(marker.getPosition());
        map.fitBounds(bounds);
       else 
        alert("geocode of " + address + " failed:" + status);
      
    );


function infoWindow(marker, map, title, address, url) 
  google.maps.event.addListener(marker, 'click', function() 
    var html = "<div><h3>" + title + "</h3><p>" + address + "<br></div><a href='" + url + "'>View location</a></p></div>";
    iw = new google.maps.InfoWindow(
      content: html,
      maxWidth: 350
    );
    iw.open(map, marker);
  );


function createMarker(results) 
  var marker = new google.maps.Marker(
    icon: 'http://maps.google.com/mapfiles/ms/icons/blue.png',
    map: map,
    position: results[0].geometry.location,
    title: title,
    animation: google.maps.Animation.DROP,
    address: address,
    url: url
  )
  bounds.extend(marker.getPosition());
  map.fitBounds(bounds);
  infoWindow(marker, map, title, address, url);
  return marker;
html,
body,
#map_canvas 
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div id="map_canvas" style="border: 2px solid #3872ac;"></div>

【讨论】:

【参考方案2】:

步骤一

首先,您必须为此创建地图位置,您想在 Web 应用程序的哪个位置添加此地图。因此,首先创建 JSP/HTML/ASP 页面,您必须在其中创建要显示地图的位置。

<div id="map_canvas" style="width: 1350px; height: 500px"></div>

第二步

下面我编写脚本,您可以使用它在您的网络应用程序上查看地图。

<script src="https://maps.googleapis.com/maps/api/js"></script>
<script type="text/javascript"
src="http://maps.google.com/maps/api/js?sensor=TRUEORFALSE"></script>
<script type="text/javascript">
var map;
var markers;
function initialize() 

    $
            .ajax(

                type : "POST",
                url : "Your Servlet Name", //Servlet Name
                data : $("#FormID"),

                success : function(responseJson) 


                    var result = $.parseJSON(responseJson);
                    markers = result;

                    // Below mapOptions var includes styling maps and zoom level of your map, it also includes mapTypeId.
                    var mapOptions = 
                        center : new google.maps.LatLng(
                                markers[0].latitude, markers[0].longitude),
                        zoom : 5,
                        scrollwheel: false, 
                        styles : [ 
                            "featureType" : "administrative",
                            "elementType" : "labels.text.fill",
                            "stylers" : [ 
                             "color" : "#444444"
                             ]
                           , 
                            "featureType" : "landscape",
                            "elementType" : "all",
                            "stylers" : [ 
                             "color" : "#f2f2f2"
                             ]
                           , 
                            "featureType" : "poi",
                            "elementType" : "all",
                            "stylers" : [ 
                             "visibility" : "off"
                             ]
                           , 
                            "featureType" : "poi.park",
                            "elementType" : "geometry.fill",
                            "stylers" : [ 
                             "visibility" : "on"
                            , 
                             "color" : "#1ba093"
                             ]
                           , 
                            "featureType" : "road",
                            "elementType" : "all",
                            "stylers" : [ 
                             "saturation" : -100
                            , 
                             "lightness" : 45
                             ]
                           , 
                            "featureType" : "road.highway",
                            "elementType" : "all",
                            "stylers" : [ 
                             "visibility" : "simplified"
                             ]
                           , 
                            "featureType" : "road.arterial",
                            "elementType" : "labels.icon",
                            "stylers" : [ 
                             "visibility" : "off"
                             ]
                           , 
                            "featureType" : "transit",
                            "elementType" : "all",
                            "stylers" : [ 
                             "visibility" : "off"
                             ]
                           , 
                            "featureType" : "water",
                            "elementType" : "all",
                            "stylers" : [ 
                             "color" : "#00748c"
                            , 
                             "visibility" : "on"
                             ]
                            ],
                        mapTypeId : google.maps.MapTypeId.ROADMAP
                    ;
                    map = new google.maps.Map(document
                            .getElementById("map_canvas"), mapOptions);
                    addYourLocationButton(map,marker);  
                    //Create and open InfoWindow.
                    var infoWindow = new google.maps.InfoWindow();                      

                    for (var i = 0; i < markers.length; i++) 
                        var data = markers[i];

                        var myLatlng = new google.maps.LatLng(
                                data.latitude, data.longitude);
                        var marker = new google.maps.Marker(
                            position : myLatlng,
                            animation: google.maps.Animation.DROP,
                            map : map,
                            title : //Any title that you want to display while cursor over the marker.
                        );

                        //Click event 
                        (function(marker, data) 
                            google.maps.event
                                    .addListener(
                                            marker,
                                            "click",
                                            function(e)                                                    
                                                infoWindow
                                                        .setContent("<div style = 'width:300px;min-height:50px'>+Write information about your location if you want.+"</div>");
                                                infoWindow
                                                        .open(map, marker);
                                            );
                        )(marker, data);

                    

                

            );


【讨论】:

【参考方案3】:

function buildMapWithMultipleBuyerLocations(buyerLocations) 
  const infowindow = new google.maps.InfoWindow();
  const geocoder = new google.maps.Geocoder();
  const map = new google.maps.Map(document.getElementById('map'), 
    zoom: 13,
    center: new google.maps.LatLng(-23.5489, -46.6388),
    mapTypeId: google.maps.MapTypeId.ROADMAP,
  );

  let latAverage = 0;
  let lngAverage = 0;
  buyerLocations.forEach(function(buyerLocation, index) 
    geocoder.geocode('address': buyerLocation.location, function(results, status) 
      if (status == google.maps.GeocoderStatus.OK) 
        const latitude = results[0].geometry.location.lat();
        const longitude = results[0].geometry.location.lng();
        // calc center of map by each
        if (index === 0) 
          latAverage = latitude;
          lngAverage = longitude;
         else 
          latAverage = ((latAverage + latitude) / 2);
          lngAverage = ((lngAverage + longitude) / 2);
        

        map.setCenter(new google.maps.LatLng(latAverage, lngAverage));

        setLocation(map, infowindow, longitude, latitude);
      
    );
  );


function setLocation(map, infowindow, longitude, latitude) 
  const marker = new google.maps.Marker(
    position: new google.maps.LatLng(latitude, longitude),
    map: map,
  );

  google.maps.event.addListener(
    marker,
    'click',
    (function (marker) 
      return function () 
        infowindow.setContent(buyerLocation.location)
        infowindow.open(map, marker)
      ;
    )(marker)
  );


const response = 
  data: 
    buyerLocations: [
      
        id: 2,
        location: 'Setor D Sul QSD 37 - Taguatinga, Brasília - DF, Brasil',
        addressDetails: 'Casa da leia',
        street: '',
        zipcode: '72020-370',
        city: 'Brasília',
        state: 'DF',
        name: 'love',
        responsibleDelivery: 
          name: 'Ruan Herculano',
          email: 'ruannawe95@gmail.com',
          phoneNumber: '(61) 98125-7366'
        
      ,
      
        id: 1,
        location: 'Setor E Sul QSE 19 - Taguatinga, Brasília - DF, Brasil',
        addressDetails: '',
        street: '',
        zipcode: '',
        city: '',
        state: '',
        name: 'Setor E Sul QSE 19 - Taguatinga, Brasília - DF, Brasil'
      
    ]
  


const  data  = response;
const  buyerLocations  = data;
buildMapWithMultipleBuyerLocations(buyerLocations);
<script
type="text/javascript"
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCTrSO0GAJbjDBLmxR3xOl-GjpNOUacrw0&libraries=places">
</script>
<div id="#map"></div>

【讨论】:

以上是关于使用 Google Maps JavaScript API v3 和 Geocoding API 映射多个位置的主要内容,如果未能解决你的问题,请参考以下文章

Google Maps JavaScript API 警告:NoApiKeys

Google Maps Javascript API 移动性能问题

JavaScript 使用“我的地图”中的.kml文件的Google Maps API

Google Maps Javascript API、DirectionsService、国家列表

从 google maps 地方 api 读取 json 文件(使用 javascript 或 php)

将 Google“我的地图”图层添加到 Google Maps Javascript API