Force user to select Address from Google Map API Autocomplete result on TextBox Blur in jQuery

Last Reply 2 months ago By pandeyism

Posted 2 months ago

hello,

Force user to select Address from Google Map API Autocomplete result in jQuery 

i am using this snippet its working fine, instead of validating on button click even i want to validate it on texbox blur event

You are viewing reply posted by: pandeyism 2 months ago.
Posted 2 months ago

Hi nauna,

Refer below sample.

HTML

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?libraries=places&key=AIzaSyAmSZwEGMWpCdpj0_3I-IzAkyF2NOF0AD8"></script>
<script type="text/javascript">
    var isPlaceChanged = false;
    google.maps.event.addDomListener(window, 'load', function () {
        var places = new google.maps.places.Autocomplete(document.getElementById('txtPlaces'));
        google.maps.event.addListener(places, 'place_changed', function () {
            isPlaceChanged = true;
            var geocoder = new google.maps.Geocoder();
            var place = places.getPlace();
            var address = place.formatted_address;
            geocoder.geocode({ 'address': address }, function (results, status) {
                if (status == google.maps.GeocoderStatus.OK) {
                    var latitude = results[0].geometry.location.lat();
                    var longitude = results[0].geometry.location.lng();
                    var mapOptions = { center: new google.maps.LatLng(latitude, longitude), zoom: 15, mapTypeId: google.maps.MapTypeId.ROADMAP };
                    var map = new google.maps.Map(document.getElementById("dvMap"), mapOptions);
                    var marker = new google.maps.Marker({ position: new google.maps.LatLng(latitude, longitude), map: map });

                } else {
                    alert("Request failed.")
                }

            });
        });
        $("#txtPlaces").blur(function () {
            if (!isPlaceChanged) {
                alert($("#txtPlaces").val());
            }
            else {
                alert("Please Enter valid location");
            }
        });
    });
</script>
<span>Location:</span>
<input type="text" id="txtPlaces" style="width: 250px" placeholder="Enter a location" />
<asp:requiredfieldvalidator id="valName" controltovalidate="txtPlaces" runat="server"
    errormessage="*Please Enter valid location" forecolor="Red" />
<div id="dvMap">
</div>

Screenshot