通过标记的名称获取标记的位置

时间:2013-04-29 15:58:51

标签: javascript google-maps

我如何获得var ble = new google.maps.Marker职位?我已经尝试了ble.getPosition().lat();但是它不起作用我猜我没有命名标记并且正确地调用它。

   var map = new google.maps.Map(document.getElementById('map'), {
      zoom: 8,
      center: new google.maps.LatLng(55.580622, 23.104248),
      mapTypeId: google.maps.MapTypeId.HYBRID 
    });


var london = new google.maps.LatLng(56, 22);
    var MyApp = {};

function HomeControl(controlDiv, map) {
  controlDiv.style.padding = '5px';
  var controlUI = document.createElement('div');
  controlUI.appendChild(controlText);

  google.maps.event.addDomListener(controlUI, 'click', function() {
        window.blia = new google.maps.Marker({
        position: london,
        draggable:true,
        map: map,
      });
  });
}

var aa = blia.getPosition();

  var homeControlDiv = document.createElement('div');
  var homeControl = new HomeControl(homeControlDiv, map);
  map.controls[google.maps.ControlPosition.TOP_RIGHT].push(homeControlDiv);

    var directionsService = new google.maps.DirectionsService();
var directionsDisplay = new google.maps.DirectionsRenderer();

    var infowindow = new google.maps.InfoWindow();

    var marker, i;

    for (i = 0; i < locations.length; i++) {  
      marker = new google.maps.Marker({
        position: new google.maps.LatLng(locations[i][1], locations[i][2]),
        map: map,
        icon: 'peace.png'
      });

      google.maps.event.addListener(marker, 'click', (function(marker, i) {
        return function() {
          MyApp.xxx = this.position;
          alert(aa);
          infowindow.setContent('x' + name[i][3] + '' + name[i][4] + 'x');
          infowindow.open(map, marker);

        var request = {
         origin: MyApp.xxx, 
         destination: MyApp.posit,
         travelMode: google.maps.DirectionsTravelMode.DRIVING
     };

        directionsService.route(request, function(response, status) {
        if (status == google.maps.DirectionsStatus.OK) {
         directionsDisplay.setDirections(response);
       }
       })

        }
      })(marker, i));
    }
directionsDisplay.setMap(map);

1 个答案:

答案 0 :(得分:0)

如果我们对HomeControl函数进行一些更改,它应该可以工作:

function HomeControl(controlDiv, map) { 
  controlDiv.style.padding = '5px'; 
  var controlUI = document.createElement('div'); 
  controlDiv.appendChild(controlUI); 

  var controlText = document.createElement('div'); 
  controlText.innerHTML = '<strong>Trigger</strong>'; 
  controlUI.appendChild(controlText);  

  google.maps.event.addDomListener(controlUI, 'click', function() { 
    MyApp.defaultmarker = new google.maps.Marker({ 
      position: map.getCenter(), 
      draggable:true, 
      map: map 
    }); 
  });
}
  • 所有html元素都需要附加到controlDiv
  • 中传递的元素
  • 变量london未在函数内部设置,因此我们应该将标记放在地图的中心。
  • 将新标记添加到全局MyApp,以便在单击控件按钮后可用。

删除此行var aa = blia.getPosition();,因为没有设置blia(在新代码的情况下是MyApp.defaultmarker),直到单击控件之后,你应该没问题。