在两个标记之间绘制路线

Draw route between two markers

我正在学习如何使用 Ext.js 开发 Web 应用程序,并且我正在使用 Google 地图 API 在我的页面中显示地图。

我为两个不同的位置添加了两个标记,我想在这两个标记之间画一条折线,我该怎么做?

我的代码:

<html>

<head>
    <link rel="stylesheet" type="text/css" href="../extjs/resources/css/ext-all.css">
    <script type="text/javascript" src="../extjs/ext-all.js"></script>
    <script src="https://maps.googleapis.com/maps/api/js?v=3&key=AIzaSyCV2QUPhqKB67SnuoQLO573e5N2yIaQiwQ"></script>

    <script type="text/javascript" src="http://docs.sencha.com/extjs/4.2.0/extjs-build/examples/ux/GMapPanel.js"></script>

</head>

<body></body>

<script type="text/javascript">

    Ext.onReady(function() {
        var w = Ext.create('Ext.window.Window', {

            height: 400,
            width: 600,
            layout: 'fit',
            header: false,
            border: false,
            style: 'padding: 0; border-width: 0;',
            closable: false,
            draggable: false,
            height: Ext.getBody().getViewSize().height,
            width: Ext.getBody().getViewSize().width,
            items: [{
                xtype: 'gmappanel',
                region: 'center',
                cls: 'reset-box-sizing',
                center: new google.maps.LatLng(51.50733,-0.1977981),
                markers: [{
                    lat: 51.50733,
                    lng: -0.1977981,
                    marker:  {title: 'Location 1'},
                    listeners: {
                        click: function(e){
                            Ext.Msg.alert('Its fine', 'and its art.');
                        }
                    }
                },{
                    lat: 53.4083509,
                    lng: -3.0616123,
                    marker: {title: 'Location 2'}
                }],
                mapOptions: {
                    zoom: 16,
                    mapTypeId: google.maps.MapTypeId.ROADMAP
                }
            }]
        });

        w.show();

    });
</script>

</html>

我一直在寻找一些代码,我找到了这个绘制折线的代码,但它说 "InvalidValueError: setMap: not an instance of Map "

var flightPathCoordinates = [
    {lat: 37.772, lng: -122.214},
    {lat: 21.291, lng: -157.821},
    {lat: -18.142, lng: 178.431},
    {lat: -27.467, lng: 153.027}
];

var flightPath = new google.maps.Polyline({
    path: flightPathCoordinates,
    strokeColor: '#FF0000',
    strokeOpacity: 1.0,
    strokeWeight: 2
});

flightPath.setMap(w);

谢谢。

Polyline 的 setMap 方法有一个必需的参数 - google 地图的一个实例。 (Google Maps JS API)

你的折线代码很好,但是当你调用 setMap 时你传递了变量 w,我假设它是你的 ExtJS window,当你需要传递它时实际的 [=31] =] 地图实例。可以通过使用 gmappanel class 的 gmap 属性 来访问。要从您的 window 到达 gmappanel class,您可以通过执行 gmappanel = w.down('gmappanel') 使用 down 方法 (ExtJS API) 或者您可以只得到它,因为你知道它是 window 包含的唯一项目 gmappanel = w.items.first();

然后您只需执行 gmap = gmappanel.gmap 即可获得实际的 google 地图实例。

因此,在您的第二个代码块中,只需将最后一行替换为:

flightPath.setMap(w.down('gmappanel').gmap);