HungryDB
HungryDB

Reputation: 575

How to change geolocation dynamically for google places api

I am working on google places api in which first user selects city and enters address in text field to get locations specific for that city. For this i have used circle bounds.

Now when user changes cities i need to re-initialize google place api to apply new circle bounds. I have used following script.

<select name="cities" id="cities" onchange="initialize()">
        <option value="0">Select City</option>
        <option value="1" lat="40.7128" long="74.0059">Newyork</option>
        <option value="2" lat="34.0522" long="118.2437">Los Angeles</option>
        <option value="3" lat="42.3601" long="71.0589">Boston</option>
    </select>
    <input id="searchTextField" type="text" size="50" placeholder="Enter a location" autocomplete="on">

<script src="http://maps.googleapis.com/maps/api/js?sensor=false&amp;libraries=places" type="text/javascript"></script>
<script type="text/javascript">

    function initialize() 
    {
        var input = document.getElementById('searchTextField');
        var lat  = jQuery('#cities option:selected').attr('lat');
        var long = jQuery('#cities option:selected').attr('long');

        //alert(lat+' == '+long);

        var geolocation = {
            lat: lat,
            lng: long
        };
        var circle = new google.maps.Circle({
            center: geolocation,
            radius: 50
        });

        var options = {
            componentRestrictions: {country: "us"}
        };

        var temp = new google.maps.places.Autocomplete(input, options);
        temp.setBounds(circle.getBounds());
    }


    google.maps.event.addDomListener(window, 'load', initialize);

</script>

Upvotes: 0

Views: 865

Answers (1)

Vinay
Vinay

Reputation: 7674

You should have mentioned the exact problem you were facing , that would have helped me think in the right direction but anyway your code looked normal so gave it a go and found these issues

1.When construction LatLngLiteral like this

   var geolocation = {
       lat: lat,
       lng: long
   };

when passing this to google function the values are expected to be numbers rather than string.May be you were getting this error "not a LatLng or LatLngLiteral: in property lat: not a number" because typeof lat would give "string"

In order to conform you need to convert them using parseFloat .Now typeof parseFloat(lat) would give "number"

   var geolocation = {
       lat: parseFloat(lat),
       lng: parseFloat(long)
   };

2.Since US lies on west of GMT so all states have a negative longitude but you were using positive it should've been like this

    <option value="1" lat="40.7128" long="-74.0059">Newyork</option>
    <option value="2" lat="34.0522" long="-118.2437">Los Angeles</option>
    <option value="3" lat="42.3601" long="-71.0589">Boston</option>

Upvotes: 1

Related Questions