kaiser
kaiser

Reputation: 22363

Google Geocoding - function does not work

Setup: I have a map with a single marker and a set of input fields. The map/init fn runs on window load.

What's working: reverse geocoding: I drag & drop the marker around and the input fields (street, nr, postal code, city, country) update through the mb_map.geocodePosition() function.

Task: Now I wanted to add normal geocoding (Address > latLng) using the same input fields to set an address and move the marker around. The function that calls normal geocoding is triggered by a button onClick="mb_map.encodeAddress()" event.

Problem: For some reason, the function doesn't get any argument and console.log() returns nothing. Instead the page reloads. I wrote a comment in the code below to help you easier finding the part where it stopped working.

<script type="text/javascript">
    /**
     * Global public map object & functions
     * @since   0.1
     */
    var mb_map = {
        map:        null,
        marker:     null,

        geocoder:   new google.maps.Geocoder(),

        lat:        null,
        lng:        null,

        input:  
        {
             street:    document.getElementById( 'location_street' )
            ,nr:        document.getElementById( 'location_nr' )
            ,zip:       document.getElementById( 'location_zip' )
            ,city:      document.getElementById( 'location_city' )
            ,country:   document.getElementById( 'location_country' )
            ,lat:       document.getElementById( 'location_lat' )
            ,lng:       document.getElementById( 'location_lng' )
        },


        /**
         * Reverse Geocoding
         * lat/lng > Address
         * 
         * @param   pos
         * @returns (object)    | Geocoded address data
         */
        geocodePosition: function( pos )
        {
            mb_map.geocoder.geocode(
            {
                latLng: pos
            }
            ,function ( responses )
            {
                if ( responses && responses.length > 0 )
                {
                    // THIS WORKS PERFECT
                    console.log( responses[0] );
                    mb_map.updateMarkerAddress( responses[0] );
                }
                else
                {
                    mb_map.updateMarkerAddress( 'Cannot determine address at this location.' );
                }
            } );
        },



        /**
         * Geocoding
         * Address > lat/lng
         */
        encodeAddress: function() 
        {
            var address_formated = 
                    mb_map.input.street.value 
                +   " "
                +   mb_map.input.nr.value
                +   ", " 
                +   mb_map.input.zip.value
                +   ", " 
                +   mb_map.input.city.value 
                +   ", " 
                +   mb_map.input.country.value;

            mb_map.geocoder.geocode(
            {
                // address: address_formated 
                // FOLLOWING LINE IS ONLY HERE, TO GET AN EASIER EXAMPLE
                address: 'Lisbon, PT'
            }
            ,function( responses, status ) 
            {
                // THIS IS WHERE NOTHING WORKS
                console.log( responses );
                if ( status == google.maps.GeocoderStatus.OK ) 
                {
                    mb_map.map.setCenter( responses[0].geometry.location );
                    mb_map.updateMarkerAddress( responses[0].geometry.location );
                    mb_map.marker = new google.maps.Marker( 
                    {
                         map:       mb_map.map
                        ,position:  responses[0].geometry.location
                    } );
                }
                else 
                {
                    alert( "Geocode was not successful for the following reason: " + status );
                }
            } );
        },


        /**
         * Update input fields on marker drop
         * 
         * @param   str
         * @returns void
         */
        updateMarkerAddress: function( str )
        {
            // not shown as not relevant
        },


        /**
         * Setup map & marker
         * 
         * @constructor
         */
        init: function()
        {
            if ( navigator.geolocation )
            {
                navigator.geolocation.getCurrentPosition( function ( position )
                {
                    mb_map.lat      = position.coords.latitude;
                    mb_map.lng      = position.coords.longitude;

                    var latLng      = new google.maps.LatLng( mb_map.lat, mb_map.lng );

                    mb_map.map      = new google.maps.Map( document.getElementById( 'map-container' ),
                    {
                        zoom:       8,
                        center:     latLng,
                        mapTypeId:  google.maps.MapTypeId.ROADMAP
                    } );
                    mb_map.marker   = new google.maps.Marker(
                    {
                        position:   latLng,
                        title:      'Location',
                        map:        mb_map.map,
                        draggable:  true
                    } );

                    // Update current position info.
                    mb_map.geocodePosition( latLng );
                } );
            }
        }
    };


    /**
     * INIT on window load
     */
    google.maps.event.addDomListener( window, 'load', mb_map.init );
</script>

Thanks!


Edit: As per comment, here's my markup:

<div id="map-container" style="min-width: 235px; height: 300px;">loading...</div>
<input type="submit" name="encode" id="encode" class="button-primary" value="Encode" onclick="mb_map.encodeAddress()">

Upvotes: 0

Views: 1869

Answers (1)

Bryan Weaver
Bryan Weaver

Reputation: 4473

You said the page is reloading when you click the button. It looks like the button is causing a post back and resetting the map before the geocoder callback function is finished. Are you using an ASP.Net button or a standard HTML input button?

In jQuery there is a method to stop a post back: event.preventDefault(). Alternately, I believe you can add a return false to the onclick event.

onClick="mb_map.encodeAddress();return false;"

UPDATE:

You have scope issues. you address_formatted variable is undefined because all of your input properties are undefined.

if you try to access the mb_map.input values in the encodeAddress function they are all undefined.

You could add another function that gets the address:

getAddress: function() {
    var address = document.getElementById('location_zip').value 
                  + ", " +  
                  document.getElementById('location_country').value;
    return address;
},

then change the encodeAddress function to call the new function:

/**
 * Geocoding
 * Address > lat/lng
 */
encodeAddress: function() {    

    mb_map.geocoder.geocode({

        //access the inputs with a function
        address: mb_map.getAddress()

    }, function(responses, status) {

        console.log(responses);

        if (status == google.maps.GeocoderStatus.OK) {
            mb_map.map.setCenter(responses[0].geometry.location);
            mb_map.updateMarkerAddress(responses[0].geometry.location);
            mb_map.marker = new google.maps.Marker({
                map: mb_map.map,
                position: responses[0].geometry.location
            });
        }
        else {
            alert("Geocode was not successful for the following reason: "
                   + status);
        }
    });
},

Here is the fiddle of it working.

Upvotes: 1

Related Questions