Branndon
Branndon

Reputation: 505

Google Maps API 3 - geocode is not working right

Here is my current code (i feel the problem is in my codeAddress function):

<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>`
<script>
    var geocoder;
    var map;
    function initialize() {
    geocoder = new google.maps.Geocoder();
    var latlng = new google.maps.LatLng(-34.397, 150.644);
    var mapOptions = {
        zoom: 8,
        center: latlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    }
    map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
    }

    function codeAddress() {
    var address = document.getElementById("address").text;
    geocoder.geocode( { 'address': address}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
        map.setCenter(results[0].geometry.location);
        var marker = new google.maps.Marker({
            map: map,
            position: results[0].geometry.location
        });
        } else {
        alert("Geocode was not successful for the following reason: " + status);
        }
    });
    }

    google.maps.event.addDomListener(window, 'load', codeAddress);
    google.maps.event.addDomListener(window, 'load', initialize);
</script>
<div id="map-canvas" style="width: 100%; height: 320px;" ></div>
<div id="address">92867</div>

What I want to do is when the page loads, the address will be populated via PHP. I want the codeAddress to run with the populated address. How can I tweak this script to replace this var latlng = new google.maps.LatLng(-34.397, 150.644); with the correct code for my specified address.

Upvotes: 3

Views: 349

Answers (1)

Dr.Molle
Dr.Molle

Reputation: 117354

  1. remove
    google.maps.event.addDomListener(window, 'load', codeAddress);
    and add this:
    codeAddress()
    to the end of initialize() , to ensure that the map has been created when codeAddress(); will be executed

  2. replace this line:
    var address = document.getElementById("address").text;
    by that line:
    var address = document.getElementById("address").firstChild.data;
    There is no text-property for a <div/>

Upvotes: 3

Related Questions