Реализация маршрутов Google Maps в Sencha Touch MVC - PullRequest
1 голос
/ 28 июня 2011

У меня есть местный магазин, в котором есть адреса. Я просматриваю адрес и нажимаю «диск», который запускает следующий код в контроллере:

showDirections: function(dataObj) {
        var directionsDisplay = new google.maps.DirectionsRenderer();
        var directionsService = new google.maps.DirectionsService();

        var start = '915 4th st, modesto, ca';

        var end = dataObj.data.get('address').value  + ' ' +
        dataObj.data.get('city').value + ' ' +
        dataObj.data.get('state').value + ' ' +
        dataObj.data.get('zip').value;

        var model = dataObj.model;

        var contactDrive = new MyApp.ContactDrivePanel(start, end, model);
        console.log(model);
        console.log(contactDrive)

        MyApp.viewport.setActiveItem(contactDrive, {type:'slide', direction:'left'});


    }

Это загрузит следующий вид:

MyApp.ContactDrivePanel = Ext.extend(Ext.Panel, {


            layout: 'fit',

            address: "",
            start: "",
            end: ""


            ,model: null

            ,constructor : function(start, end, model) {
                console.log('hello');
                this.start = start;
                this.end = end;
                this.model = model;
                console.log(this.model);
                console.log('start: ' + start);
                console.log('end: ' + end);

                MyApp.ContactDrivePanel.superclass.constructor.apply(this);
            }

            ,initComponent : function () {
                var directionDisplay;
                var map;
                console.log("initializing ContactDrivePanel");
                this.dockedItems = this.buildToolbars();


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

                var thestart = geocoder.geocode({'address': start});
                var theend = geocoder.geocode({'address': end});

                var request = {
                    origin: this.start,
                    destination: this.end,
                    travelMode: google.maps.DirectionsTravelMode.DRIVING
                };

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

                var pnl = new Ext.Panel({
                            fullscreen: true,
                            items     : [
                                {
                                    xtype             : 'map',
                                    useCurrentLocation: true
                                }
                            ]
                        });


                MyApp.ContactDrivePanel.superclass.initComponent.call(this);


            },

            buildToolbars : function() {
                console.log('Model in buildToolbars: ' + this.model);
                return [
                    {
                        xtype : 'toolbar',
                        dock  : 'top',
                        title: 'Map Contact Address',
                        items : [
                            {
                                text : 'Back'
                                ,ui   : 'back'
                                ,handler : this.back
                                ,scope: this // This is necessary for scoping the object's model object correctly
                            }
                        ]
                    }
                ]
            },

            back : function(btn, evt) {
                console.log('Model in the back function: ' + this.model);
                Ext.dispatch({
                            controller : 'ContactFormPanelController'
                            ,action    : 'returnToDetails'
                            ,model: this.model
                        });
            },

            setModel : function(model) {
                this.model = model;
            }

        });

// Sp that lazy instantiation may be used in creating ContactMapPanels
Ext.reg('contactDrive', MyApp.ContactDrivePanel);

Как видите, я пробовал несколько разных вещей. Я попытался геокодировать адрес, который дает мне ошибку: «Uncaught TypeError: Невозможно вызвать метод« apply »из неопределенного» * ​​1007 *

А без геокодирования это просто не работает. Я получаю карту на экране, но это все. И, конечно же, это центр Пало-Альто.

Ответы [ 3 ]

4 голосов
/ 03 июля 2011

добавить эту строку после directionsDisplay.setDirections (response):

directionsDisplay.setMap(map.map);

, чтобы связать направления Отображение с картой

1 голос
/ 30 июня 2011

Проверьте это приложение сенсорного Сенча. Это именно то, что вы ищете. Это может решить вашу проблему.

http://septa.mobi/

0 голосов
/ 15 сентября 2011

Не уверен, поможет ли это ... Но я попробовал ваш код, а затем кучу других примеров ... Я столкнулся с этим (который, кажется, работает нормально)

Для карты:

pos = new google.maps.LatLng(lats, longs);
mapPanel = new Ext.Map({
        id : 'myMap',
        mapOptions : {
            center : pos,
            zoom : 20,
            mapTypeId : google.maps.MapTypeId.HYBRID,
            navigationControl: true,
            navigationControlOptions: {
                    style: google.maps.NavigationControlStyle.DEFAULT
                }
        },            

        plugins : new Ext.plugins.GMap.Tracker({
            trackSuspended : true,   //suspend tracking initially
            marker : new google.maps.Marker({
                position: pos,
                title : 'Working!!!!'
              }) 
            }), 

        listeners : {
            maprender : function(comp, map){
                var marker = new google.maps.Marker({
                     position: pos,
                     //title : 'Sencha HQ',
                     map: map
                });

                google.maps.event.addListener(marker, 'click', function() {
                     infowindow.open(map, marker);
                }); 


                setTimeout( function(){map.panTo (pos);} , 1000);

                var marker = new google.maps.Marker({
                     position: pos,
                     map: mapPanel.map
                });
            }

        }
    });

Для Направлений я использовал кнопку на панели инструментов с обработчиком:

handler: function(){

                        var directionsDisplay = new google.maps.DirectionsRenderer();
                        var directionsService = new google.maps.DirectionsService();
                        directionsDisplay.setMap(mapPanel.map);
                        //alert("ok pressed");
                        var start = "carter road, bandra, mumbai";
                        var end = "Bandra Station, Mumbai, India";
                        var request = {
                            origin:start, 
                            destination:end,
                            travelMode: google.maps.DirectionsTravelMode.DRIVING
                        };
                        directionsService.route(request, function(response, status) {
                            if (status == google.maps.DirectionsStatus.OK) {
                                directionsDisplay.setDirections(response);
                            }
                        });
                    }.........

Это то, что вы искали?Он устанавливает положение центра в любой точке, которую вы выбираете, а не в Пало-Альто ..., а также показывает карту с указаниями

...