Прототип, Google Maps Ajax API V3 - ошибки, но не уверен, почему. - g.e не определено - PullRequest
1 голос
/ 29 июня 2011

Я пытаюсь написать простую (в моей голове; D) страницу, где пользователь может ввести местоположение и отобразить его на карте.В фоновом режиме должны быть поля:

широта, долгота, масштаб

. Они должны обновляться, когда пользователь вводит новое местоположение, перемещает карту или изменяет уровень масштабирования.

Пожалуйста, найдите мой код ниже, я использую Prototype lib для этого.Начальная загрузка работает, но когда карта перемещается, я получаю сообщение об ошибке в консоли:

ge не определено - строка main.js 20

и в Zoom событие неуволена.Когда выполняется текстовый поиск, LocationFound жалуется, что SetLatLong не является функцией?

Пожалуйста, помогите, я провел последние несколько часов в кругах !!!: (

<html>
<head>
    <title>Google Maps</title>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/prototype/1.7.0.0/prototype.js"></script>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true"></script>
<script type="text/javascript">
    var Map = {
        gmap : '',
        geocoder : '',
        map_container : '',
        geocode_input : '',
        geocode_form : '',

        CreateMap : function(){
            this.map_container = $('gmap');
            this.geocode_form = $('gmap_form');
            this.geocode_input = $('gmap_input');

            try {
                this.ConfigureMap();
                this.SetDefaultLocation(); 
                this.ConfigureGeocoder();
                this.Listen();
            } catch(err) {
                console.debug(err);
            }
            },

        ConfigureMap : function() {

           var DefaultMapOptions = {
                zoom: 3,
                center: new google.maps.LatLng(43.834526782236814, -37.265625),
                mapTypeId: google.maps.MapTypeId.ROADMAP
                  };

               this.gmap = new google.maps.Map(this.map_container, DefaultMapOptions);
       },

       ConfigureGeocoder : function() {
           this.geocoder = new google.maps.Geocoder();
       },

       SetDefaultLocation : function() {
            //TODO: Check if a location string is already present
            //if (google.loader.ClientLocation) { //default to IP location if possible - not using loader anymore so comment out for now.
            //    this.SetLatLong(google.loader.ClientLocation.latitude,google.loader.ClientLocation.longitude, 8);
            //}
       },

       SetLatLong : function(lat, lon, zoomLevel){
            this.gmap.setCenter(new google.maps.LatLng(lat, lon));

            if (zoomLevel){
                this.gmap.setZoom(zoomLevel);
            }

            $('latitude').value = lat;
            $('longitude').value = lon;
        },

        Listen : function() {
           google.maps.event.addListener(this.gmap, 'dragend', this.MapMoved());
           google.maps.event.addListener(this.gmap, 'zoom_changed', this.Zoomed());
           Event.observe(this.geocode_form, 'submit', this.FindLocation(this.geocode_input));
        },

        Zoomed : function (){
            $('zoom').value = this.gmap.getZoom();
        },

        MapMoved : function(){
            console.debug('map moved');
            var position = this.gmap.getCenter();
            this.SetLatLong(position.lat(), position.lng());
        },

        FindLocation : function(location){
            if (location){
                var address = location.value;
                if (address){
                    try {
                        this.geocoder.geocode( { 'address' : address }, this.LocationFound );
                    } catch(err) {
                        console.debug(err);
                    }
            }
        }
            return false;
        },

            LocationFound : function(results, status){
            if (status == google.maps.GeocoderStatus.OK) {
            //THIS IS DYING TOO? :(
                this.SetLatLong(results[0].geometry.location.lat(), results[0].geometry.location.lng());
            } else {
                alert("Geocode was not successful for the following reason: " + status);
            }
            }
    };

    document.observe('dom:loaded', function(event){
        Map.CreateMap();
    }.bind(this));
</script>
<style>
    div#gmap {
        width: 100%;
        height: 400px;
    }
</style>
</head>
<body>
    <form action="http://maps.google.com/maps" id="gmap_form">
        <p>
            <label for="geocodeInput">Location Text:</label>
            <input type="text" name="q" id="gmap_input">
            <input type="submit" value="Zoom to place">
        </p>
    </form>
    <div id="gmap"></div>
    <p><strong>Latitude, Longitude:</strong> <input type="text" id="latitude"><input type="text" id="longitude"></span></p>
    <p><strong>Zoom:</strong> <input type="text" id="zoom"></p>
</body>

Ответы [ 2 ]

2 голосов
/ 30 июня 2011

Это работает

google.maps.event.addListener(this.gmap, 'dragend', function () { Map.MapMoved() });
0 голосов
/ 18 октября 2013

Принятый ответ не делает это очевидным, но проблема в том, что:

google.maps.event.addListener(this.gmap, 'zoom_changed', this.Zoomed());

Где:

Zoomed : function () { $('zoom').value = this.gmap.getZoom(); },

Обратите внимание, что результат of вызов zoomed (т. е. undef, который возвращает this.Zoomed ()) устанавливается в качестве обработчика событий, а не масштабируется сам;ошибка здесь (ge не определена) характерна для передачи недопустимого значения в API обработчика событий карт.

Этот код будет работать, если он будет читать:

google.maps.event.addListener(this.gmap, 'zoom_changed', this.Zoomed); 
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...