Michael Grigsby
Michael Grigsby

Reputation: 12173

jQuery Google Maps get address based on click

I am building a Google Maps feature. When the user clicks the button the jquery script should grab the address from the textbox but its not working properly. Does anybody know what all I am doing wrong?

<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false&amp;language=en"></script>
<script type="text/javascript" src="<?=base_url()?>data/gmap3.js"></script>

<script>
    $(document).ready(function() {
        function getAddress() {
            $("#addressClick").click(function() {
                $('#address').val();
            });
        }
        $("#my_map").gmap3({
            marker: {
                address: getAddress()
            }, map:{
                options:{
                    zoom: 14
                }
            }
        });
    });
</script>
<input id="address" type="text" placeholder="Please type in your address"><input type="button" value="Go to location" id="addressClick">
<div id="my_map" style=" height: 350px; width: 300px;"></div>

Upvotes: 0

Views: 1343

Answers (1)

gilly3
gilly3

Reputation: 91667

It looks like you don't want to load the map until the button is clicked. But, you are loading the map as soon as the page is ready. And you are passing undefined as the address:

address: getAddress()

The function getAddress() has no return value, so when you assign it's value to a property, the property has the value of undefined. All getAddress() does is assign a click handler to your button. Inside the click handler, the value of the text box is read, but that value is ignored.

If you want to load the map after the button is clicked, you need to move the code to load the map inside the click handler. Also, move that click handler binding outside of the getAddress() function.

$(document).ready(function() {
    $("#addressClick").click(function() {
        $("#my_map").gmap3({
            marker: {
                address: $('#address').val()
            }, map:{
                options:{
                    zoom: 14
                }
            }
        });
    });
});

Working demo: jsfiddle.net/wFxDR

Upvotes: 1

Related Questions