点击Google Maps API v3从标记中绘制折线 [英] Draw Polyline from Marker on click Google Maps API v3

查看:87
本文介绍了点击Google Maps API v3从标记中绘制折线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是 post 我前几天做了一个尝试,试图在新的方向上迎接我的挑战。我的目标是当我点击一个标记时,我希望我的多段线的原点纬度/经度与该经纬度相同。我正在运行的技巧是在哪里将线创建放在我的标记的循环中,点击存在以便线将使用标记的坐标,并对已声明的坐标进行拼写。由于我在这个函数之外声明了我的纬度/经度变量,所以这行默认为它们的值: var oLat = 10.1 var oLng = 22.1 ,而不是我for循环内的值。这是我当前的循环:

pre $ for(var i in points){
var p = points [i] ;
var latlng = new google.maps.LatLng(p [1],p [2]);

var marker = new google.maps.Marker({
position:latlng,
icon:points [i] [3],
zIndex:p [5 ],
title:p [0]
});

overviewMarkers.push(marker);


google.maps.event.addListener(marker,'click',(function(marker,i){
return function(){
infowindow.setContent (points [i] [6] +'< div id =infopanel>'+
'< input onclick =addLine();type = button value =Show Routes>' +
'< input onclick =removeLine();type = button value =Remove Routes>< / div>);
infowindow.open(map,marker)
oLat = parseFloat(this.position.lat()。toFixed(4))
oLng = parseFloat(this.position.lng()。toFixed(4))
}
} )(marker,i));
} //结束循环

我试图将行代码放在 oLng = parseFloat(this.position.lng()。toFixed(4))但是我的线不会绘制。如果我将行代码保留在整个函数之外,它将使用默认值进行绘制。行创建代码(我添加了一个提醒,只是为了确认我的var会捕获点击后的值):

$ $ $ $ $ $ $ $ var arrayLine = []
var originPoint = [new google.maps.LatLng(oLat,oLng)];
var destPoint = [new google.maps.LatLng(51.9279723,4.4904063),
new google.maps.LatLng(40.136482,-73.831299),
new google.maps.LatLng(34.0204989, -118.4117325)
];
var lineSymbol = {
path:google.maps.SymbolPath.FORWARD_OPEN_ARROW
};

(destPoint中的var d){
var t = destPoint [d];

linePath = new google.maps.Polyline({
path:[originPoint [0],[t] [0]],
strokeColor:'#4A484D',
strokeOpacity:1.0,
strokeWeight:2,
geodesic:true,
图标:[{
图标:lineSymbol,
offset:'100%' ,
重复:'60px'
}]

});
arrayLine.push(linePath)

函数setLines(map){
for(var i = 0; i< arrayLine.length; i ++){
arrayLine [I] .setMap(地图);



函数addLine(){
setLines(map);
alert(parseFloat(oLat));
}

我试图查看,但它似乎更简单一些我试图做。


  1. 您需要在标记点击侦听器中创建多段线
  2. 使用记录的方法(.getPosition(),而不是未记录的属性.position)

标记可访问,您可以获取它的位置。



  for(var i in points){
var p = points [i];
var latlng = new google.maps.LatLng(p [1],p [2]);

var marker = new google.maps.Marker({
position:latlng,
icon:points [i] [3],
zIndex:p [5 ],
map:map,
title:p [0]
});

overviewMarkers.push(marker);


google.maps.event.addListener(marker,'click',(function(marker,i){
return function(){
var originPoint = this.getPosition();
var oLat = parseFloat(this.getPosition()。lat()。toFixed(4));
var oLng = parseFloat(this.getPosition()。lng()。 toFixed(4));
for(var d in destPoint){
var t = destPoint [d];

var linePath = new google.maps.Polyline({ b $ b path:[originPoint,[t] [0]],
strokeColor:'#4A484D',
strokeOpacity:1.0,
strokeWeight:2,
geodesic:true ,
图标:[{
图标:lineSymbol,
抵消:'100%',
重复:'60px'
}],
map:地图

} );
arrayLine.push(linePath);
}
infowindow.setContent(points [i] [6] +'< div id =infopanel>'+
'< input onclick =addLine(); type = button value =显示路由>'+
'< input onclick =removeLine();type = button value =删除路由>< / div>);
infowindow.open(map,marker);
};
})(marker,i));
} //结束循环

工作小提琴


$ b 代码段:



  var map; var arrayLine = []; var overviewMarkers = []; var oLat,oLng; function initialize(){var myLatlng = new google.maps。 LatLng(0,180); var mapOptions = {zoom:1,center:myLatlng}; map = new google.maps.Map(document.getElementById(map-canvas),mapOptions); var points = [[''Karachi,Pakistan',25.0111453,67.0647043,'http://maps.google.com/intl/en_us/mapfiles/ms/micons/red-dot.png','Overview',1,'' < h4>示例文本< / h4'],['曼谷,泰国',13.7246005,100.6331108,'http://maps.google.com/intl/en_us/mapfiles/ms/micons/green-dot.png' ,'Overview',1,'< h4> Sample Text< / h4>],['Rotterdam,Netherlands',51.9279723,4.4904063,'http://maps.google.com/intl/en_us/mapfiles/ms /'1','< h4> Sample Text< / h4>],['New York,NY,USA',40.7056308,-73.9780035'http:// maps.google.com/intl/en_us/mapfiles/ms/micons/green-dot.png','Overview',1,'< h4> Sample Text< / h4>],[''Memphis,TN,USA ',35.129186,-89.9696395,'http://maps.google.com/intl/en_us/mapfiles/ms/micons/green-dot.png','Overview',1,'< h4> Sample Text< h4>']]; var infowindow = new google.maps.InfoWindow(); var originPoint = []; //为(var i的点)创建标记{var p = points [i]; var latlng = new google.maps.LatLng(p [1],p [2]); var marker = new google.maps.Marker({position:latlng,icon:points [i] [3],zIndex:p [5],map:map,title:p [0]}); overviewMarkers.push(标记); google.maps.event.addListener(marker,'click',(function(marker,i){return function(){var originPoint = this.getPosition(); var oLat = parseFloat(this.getPosition()。lat() .toFixed(4)); var oLng = parseFloat(this.getPosition()。lng()。toFixed(4)); for(var d in destPoint){var t = destPoint [d]; var linePath = new google。 maps.Polyline({path:[originPoint,[t] [0]],strokeColor:'#4A484D',strokeOpacity:1.0,strokeWeight:2,测地线:true,图标:[{icon:lineSymbol,offset:'100% ',重复:'60px'}],map:map}); arrayLine.push(linePath);} infowindow.setContent(points [i] [6] +'< div id =infopanel>'+' < input onclick =addLine();type = button value =Show Routes>'+'< input onclick =removeLine();type = button value =Remo ve Routes>< / div>'); infowindow.open(map,marker); }; })(marker,i)); } //结束循环} var arrayLine = []; var originPoint = [new google.maps.LatLng(oLat,oLng)]; var destPoint = [new google.maps.LatLng(51.9279723,4.4904063),new google.maps .LatLng(40.136482,-73.831299),new google.maps.LatLng(34.0204989,-118.4117325)]; var lineSymbol = {path:google.maps.SymbolPath.FORWARD_OPEN_ARROW}; function addLine(){setLines(map); // alert(parseFloat(oLat));} google.maps.event.addDomListener(window,'load',initialize);函数setLines(map){for(var i = 0; i< arrayLine.length; i ++) {arrayLine [i] .setMap(map); }} function removeLine(){setLines(null);}  

html,body,#map-canvas {height:100%; margin:0px; padding:0px} #panel {position:absolute; top:5px;剩下:50%; margin-left:-180px; z-index:5; background-color:#fff;填充:5px; border:1px solid#999;}#infopanel {width:200px; height:60px;}

< script src =https ://maps.googleapis.com/maps/api/js>< / script>< div id =panel> < input onclick =showFactoryMarkers(); type = button value =显示工厂> < input onclick =showCFSMarkers(); type = button value =显示CFS> < input onclick =showPortMarkers(); type = button value =显示端口> < input onclick =hideMarkers(); type = button value =全部隐藏>< / div>< div id =map-canvas>< / div>


This is a follow-up to a post I made a few days ago, in attempt to go at my challenge in a new direction. My goal is when I click on a marker, I would like the origin lat/lng of my polyline to be the same lat/lng as that marker. The trick that I am running into is where to put the line creation in my for loop of my markers where the on click exists so that the line will use the coordinates of the marker, verse the declared. Since I declare my lat/lng variables outside of this function, the line defaults to their values: var oLat = 10.1 var oLng = 22.1rather than the values inside my for loop. Here is my current for loop:

for (var i in points) {
var p = points[i];
var latlng = new google.maps.LatLng(p[1], p[2]);

var marker = new google.maps.Marker({
    position: latlng,
    icon: points[i][3],
    zIndex: p[5],
    title: p[0]     
});

overviewMarkers.push(marker);


google.maps.event.addListener(marker, 'click', (function(marker, i) {
    return function() {
    infowindow.setContent(points[i][6] + '<div id="infopanel">'+
  '<input onclick="addLine();" type=button value="Show Routes">'+
  '<input onclick="removeLine();" type=button value="Remove Routes"></div>');
      infowindow.open(map, marker)
     oLat = parseFloat(this.position.lat().toFixed(4))
     oLng = parseFloat(this.position.lng().toFixed(4))
        }      
    })(marker, i) );        
}//end for loop  

I have attempted placing my line code (below) after the oLng = parseFloat(this.position.lng().toFixed(4)) but then my line wont draw. If I keep my line code outside of the entire function, it will draw with the default values. Line creation code (I added an alert just to confirm that my var would capture the on-click value):

var arrayLine=[]
var originPoint = [new google.maps.LatLng(oLat,oLng)];
var destPoint = [new google.maps.LatLng(51.9279723,4.4904063),
                 new google.maps.LatLng(40.136482, -73.831299),
                 new google.maps.LatLng(34.0204989,-118.4117325)                 
                ];
var lineSymbol = {
    path: google.maps.SymbolPath.FORWARD_OPEN_ARROW                  
};

for (var d in destPoint) {
    var t = destPoint[d];

  var linePath = new google.maps.Polyline({
    path: [originPoint[0],[t][0]], 
    strokeColor: '#4A484D',
    strokeOpacity: 1.0,
    strokeWeight: 2,
    geodesic: true,
      icons: [{
    icon: lineSymbol,
    offset: '100%',
    repeat: '60px'
  }]

  });
   arrayLine.push(linePath)

function setLines(map) {
for (var i = 0; i < arrayLine.length; i++) {
    arrayLine[i].setMap(map);
    }
   }
  }
function addLine() {
setLines(map);
alert(parseFloat(oLat));
}   

I have attempted to look at the complex polyine example that google provides, but it seems a little more simplified then what I am attempting to do.

解决方案

  1. you need to create the polyline in the marker click listener (where the marker is accessible and you can get its position).
  2. use documented methods (.getPosition(), not undocumented properties .position)

for (var i in points) {
    var p = points[i];
    var latlng = new google.maps.LatLng(p[1], p[2]);

    var marker = new google.maps.Marker({
        position: latlng,
        icon: points[i][3],
        zIndex: p[5],
        map: map,
        title: p[0]
    });

    overviewMarkers.push(marker);


    google.maps.event.addListener(marker, 'click', (function (marker, i) {
        return function () {
            var originPoint = this.getPosition();
            var oLat = parseFloat(this.getPosition().lat().toFixed(4));
            var oLng = parseFloat(this.getPosition().lng().toFixed(4));
            for (var d in destPoint) {
                var t = destPoint[d];

                var linePath = new google.maps.Polyline({
                    path: [originPoint, [t][0]],
                    strokeColor: '#4A484D',
                    strokeOpacity: 1.0,
                    strokeWeight: 2,
                    geodesic: true,
                    icons: [{
                        icon: lineSymbol,
                        offset: '100%',
                        repeat: '60px'
                    }],
                    map: map

                });
                arrayLine.push(linePath);
            }
            infowindow.setContent(points[i][6] + '<div id="infopanel">' +
                '<input onclick="addLine();" type=button value="Show Routes">' +
                '<input onclick="removeLine();" type=button value="Remove Routes"></div>');
            infowindow.open(map, marker);
        };
    })(marker, i));
} //end for loop  

working fiddle

code snippet:

var map;
var arrayLine = [];
var overviewMarkers = [];
var oLat, oLng;

function initialize() {
  var myLatlng = new google.maps.LatLng(0, 180);
  var mapOptions = {
    zoom: 1,
    center: myLatlng
  };
  map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);

  var points = [
    ['Karachi, Pakistan', 25.0111453, 67.0647043, 'http://maps.google.com/intl/en_us/mapfiles/ms/micons/red-dot.png', 'Overview', 1, '<h4>Sample Text</h4'],
    ['Bangkok, Thailand', 13.7246005, 100.6331108, 'http://maps.google.com/intl/en_us/mapfiles/ms/micons/green-dot.png',
      'Overview', 1, '<h4>Sample Text</h4>'
    ],
    ['Rotterdam, Netherlands', 51.9279723, 4.4904063, 'http://maps.google.com/intl/en_us/mapfiles/ms/micons/green-dot.png', 'Overview', 1, '<h4>Sample Text</h4>'],
    ['New York, NY, USA', 40.7056308, -73.9780035, 'http://maps.google.com/intl/en_us/mapfiles/ms/micons/green-dot.png', 'Overview', 1, '<h4>Sample Text</h4>'],
    ['Memphis, TN, USA', 35.129186, -89.9696395, 'http://maps.google.com/intl/en_us/mapfiles/ms/micons/green-dot.png', 'Overview', 1, '<h4>Sample Text</h4>']
  ];

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

  var originPoint = [];
  // Creates markers  
  for (var i in points) {
    var p = points[i];
    var latlng = new google.maps.LatLng(p[1], p[2]);

    var marker = new google.maps.Marker({
      position: latlng,
      icon: points[i][3],
      zIndex: p[5],
      map: map,
      title: p[0]
    });

    overviewMarkers.push(marker);


    google.maps.event.addListener(marker, 'click', (function(marker, i) {
      return function() {
        var originPoint = this.getPosition();
        var oLat = parseFloat(this.getPosition().lat().toFixed(4));
        var oLng = parseFloat(this.getPosition().lng().toFixed(4));
        for (var d in destPoint) {
          var t = destPoint[d];

          var linePath = new google.maps.Polyline({
            path: [originPoint, [t][0]],
            strokeColor: '#4A484D',
            strokeOpacity: 1.0,
            strokeWeight: 2,
            geodesic: true,
            icons: [{
              icon: lineSymbol,
              offset: '100%',
              repeat: '60px'
            }],
            map: map

          });
          arrayLine.push(linePath);
        }
        infowindow.setContent(points[i][6] + '<div id="infopanel">' +
          '<input onclick="addLine();" type=button value="Show Routes">' +
          '<input onclick="removeLine();" type=button value="Remove Routes"></div>');
        infowindow.open(map, marker);
      };
    })(marker, i));
  } //end for loop  
}
var arrayLine = [];
var originPoint = [new google.maps.LatLng(oLat, oLng)];
var destPoint = [new google.maps.LatLng(51.9279723, 4.4904063),
  new google.maps.LatLng(40.136482, -73.831299),
  new google.maps.LatLng(34.0204989, -118.4117325)
];
var lineSymbol = {
  path: google.maps.SymbolPath.FORWARD_OPEN_ARROW
};

function addLine() {
  setLines(map);
  // alert(parseFloat(oLat));
}
google.maps.event.addDomListener(window, 'load', initialize);

function setLines(map) {
  for (var i = 0; i < arrayLine.length; i++) {
    arrayLine[i].setMap(map);
  }
}

function removeLine() {
  setLines(null);
}

html,
body,
#map-canvas {
  height: 100%;
  margin: 0px;
  padding: 0px
}
#panel {
  position: absolute;
  top: 5px;
  left: 50%;
  margin-left: -180px;
  z-index: 5;
  background-color: #fff;
  padding: 5px;
  border: 1px solid #999;
}
#infopanel {
  width: 200px;
  height: 60px;
}

<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="panel">
  <input onclick="showFactoryMarkers();" type=button value="Show Factories">
  <input onclick="showCFSMarkers();" type=button value="Show CFS">
  <input onclick="showPortMarkers();" type=button value="Show Ports">
  <input onclick="hideMarkers();" type=button value="Hide All">
</div>
<div id="map-canvas"></div>

这篇关于点击Google Maps API v3从标记中绘制折线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆