Get map while typing address and get address by dragging marker in google maps

Suppose you have a contact form with a input field called location or address. Now you want to show user his or her location in google maps based on address he or she typed. Or you need their location co-ordinate (latitude and longitude) for that address. To convert addresses into geographic coordinates and geographic coordinates to address google maps has Geocoding API. Full documentation for Geocoding API is here https://developers.google.com/maps/documentation/geocoding/. To use this API you might need a api key.

If you are interested you can click here to see what we are going to do.

Lets start with the HTML and CSS. First we need to create a input field and a container for the map. In this post we’ll also create two input field for latitude and longitude. In real world scenario you might want these two fields to be hidden.

<div class="wrapper">
    <label for="location">Type Location Here : <input type="text" name="location" id="location" /></label>
    <label for="lat">Lat : <input type="text" name="lat" id="lat" /></label>
    <label for="lng">lng : <input type="text" name="lng" id="lng" /></label>
    <div id="map-canvas" class="hidden"></div>
</div>
.wrapper { width: 800px; }
.hidden { display: none; }
#map-canvas { height: 300px; margin: 10px 0; }

Please note that we kept the map container hidden.

That’s all we need to do with HTML and CSS. Now we’ll move to JS part. We’ll use jQuery here as our javascript library.
Now add jQuery and google maps library into your HTML head

<script type="text/javascript" src="//code.jquery.com/jquery-1.11.0.js"></script>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&amp;sensor=false"></script>

Now we need to initialize map and marker object. First we will set our map center at 0,0 co-ordinate.

    var mapOptions = {
        center: new google.maps.LatLng(0, 0),
        zoom: 16
    },
    map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions),
    marker = new google.maps.Marker({
        position: map.getCenter(),
        map: map,
        title: 'Drag to set position',
        draggable: true,
        flat: false
    });

Google maps Geocoding API provides multiple set results for a address. When user types the address we’ll take that address as a string and make a ajax request to geocoding api and use the first result to show the map. Do not forget to resize the map after shown. To resize all we need to do is trigger resize event.

//get location from address
    $('#location').keyup(function() {
        if ($('#map-canvas').hasClass('hidden')) {
            $('#map-canvas').removeClass('hidden').fadeIn().addClass('show');
            google.maps.event.trigger(map, 'resize');
        }
        var address = $(this).val();
        if (address.length == 0) {
            $('#map-canvas').removeClass('show').fadeOut().addClass('hidden');
        }
        url = 'https://maps.googleapis.com/maps/api/geocode/json?address=' + address + '&sensor=false';
        $.get(url, function(data) {
            if (data.status == 'OK') {
                map.setCenter(data.results[0].geometry.location);
                marker.position=map.getCenter();
                $('#lat').val(data.results[0].geometry.location.lat);
                $('#lng').val(data.results[0].geometry.location.lng);

            }
        });
    });

If you want your user to set address from the map by dragging the marker on the map you can also do that by using Geocoding API. This api also provides address from co-ordinate. Now we’ll do just the opposite to what we have done before.

google.maps.event.addListener(marker, 'dragend', function() {
        latlng = marker.getPosition();
        url = 'https://maps.googleapis.com/maps/api/geocode/json?latlng='+ latlng.lat() + ',' + latlng.lng() + '&sensor=false';
        $.get(url, function(data) {
            if (data.status == 'OK') {
                map.setCenter(data.results[0].geometry.location);                
                if (confirm('Do you also want to change location text to ' + data.results[0].formatted_address) === true) {
                    $('#location').val(data.results[0].formatted_address);
                    $('#lat').val(data.results[0].geometry.location.lat);
                    $('#lng').val(data.results[0].geometry.location.lng);
                }
            }
        });
        
    });

That’s all. You can get the full code here http://jsfiddle.net/dct2spzt/5/. Thank you for reading the post.

Simple jQuery popup on page load

If you need to show some information or advertisement or newsletter sign up or something else when page loads you might want to show this on a popup. In this post I’ll show you how to create one of this type of popup with jQuery. Here is a demo of what we are going to build. To create such popup we need to create an element that spans through out the screen working as a mask and on top of it in the middle of the view port we can show our contents. Let’s first make the masking element. Let’s call it shadow element. This can be created by many ways. This time we shall create a jQeury object and on page load and prepend it to body tag. For this javascript code will be

var shadow = $('<div id="shadowElem"></div>');
$(document).ready(function() {
	$('body').prepend(shadow);
});

Now adding some style to it.

#shadowElem {
	position: absolute;
	top: 0;
	left: 0;
	width: 100%;
	height: 100%;
	background-color: black;
	opacity: 0.3;
}

Now we need to create our popup on top of this shadow element. Lets call it drop element. We are calling it drop element because we want to add some effect like to coming down from top to middle. To create popup html put following html tags inside your page body tag. This will hold our popup contents.

<div id="dropElem"><!-- wrapper -->
	<div id="dropContent"><!-- Inside this tag put your popup contents -->
		<div id="dropClose">X</div><!-- this will serve as close button -->
		<img src="http://beautiful-island.50webs.com/beautiful-island/beautiful-island.jpg" alt="blue" /><!-- using this image as demo -->
	</div>
</div>

Our drop element needed to be hidden at first at should be on top of every other content of our page. Also we needed to position our close button properly. Now css to achieve is

#dropElem {
	display: none;
	position: absolute;
	top: 0;
	border-radius: 10px 10px 10px 10px;
	box-shadow: 0 0 25px 5px #999;
	padding: 20px;
	background: #fff;
}
#dropContent {
	position: relative;
}
#dropClose {
	position: absolute;
	z-index: 99999;
	cursor: pointer;
	top: -32px;
	right: -30px;
	padding: 5px;
	background-color: black;
	border-radius: 6px 6px 6px 6px;
	color: #fff;
}

Now we need to position our drop element in the middle of the page with some animation. First we are going to calculate the left and top position for the popup to place it on the middle of the screen. To do this we need to know the dimension of the view port and dimension of our popup. We can get width and height of the view port by $(window).width() and $(window).height() and our popup content width and height can be obtain by $(‘#dropElem’).outerWidth(true) and $(‘#dropElem’).outerHeight(true). If you want to know more about outerWitdth and outerHeight methods please click here and here. Now our popup left position will be subtraction between half of view port width and half of our drop element width. We can get the top position in the same way by subtracting half of view port height and half of our drop element height. We must do this calculation inside window load event. Otherwise we might get unexpected results. After this we are going place our popup top middle of the view port and from there we shall animate this to center. Here is our code.

	var speed = 1000; //animation speed
	
	$(window).load( function() {
		screenHeight = $(window).height();
		screenWidth = $(window).width();
		elemWidth = $('#dropElem').outerWidth(true);
		elemHeight = $('#dropElem').outerHeight(true)
		
		leftPosition = (screenWidth / 2) - (elemWidth / 2); 
		topPosition = (screenHeight / 2) - (elemHeight / 2);
		
                //place drop element on top middle of screen
		$('#dropElem').css({
			'left' : leftPosition + 'px',
			'top' : -elemHeight + 'px'
		});
                //some animation .. coming down from top
		$('#dropElem').show().animate({
			'top' : topPosition
		}, speed);
		//change opcity of shadow element
		shadow.animate({
			'opacity' : 0.7
		}, speed);
		//close button 
		$('#dropClose').click( function() {
			shadow.animate({
				'opacity' : 0
			}, speed);
			$('#dropElem').animate({
			'top' : -elemHeight + 'px'
		}, speed, function() {
				shadow.remove();
				$(this).remove();
			});
		});
	});

This is the full code

<!doctype html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script type="text/javascript">
	var shadow = $('<div id="shadowElem"></div>');
	var speed = 1000;
	$(document).ready(function() {
		$('body').prepend(shadow);
	});
	$(window).load( function() {
		screenHeight = $(window).height();
		screenWidth = $(window).width();
		elemWidth = $('#dropElem').outerWidth(true);
		elemHeight = $('#dropElem').outerHeight(true)
		
		leftPosition = (screenWidth / 2) - (elemWidth / 2);
		topPosition = (screenHeight / 2) - (elemHeight / 2);
		
		$('#dropElem').css({
			'left' : leftPosition + 'px',
			'top' : -elemHeight + 'px'
		});
		$('#dropElem').show().animate({
			'top' : topPosition
		}, speed);
		
		shadow.animate({
			'opacity' : 0.7
		}, speed);
		
		$('#dropClose').click( function() {
			shadow.animate({
				'opacity' : 0
			}, speed);
			$('#dropElem').animate({
			'top' : -elemHeight + 'px'
		}, speed, function() {
				shadow.remove();
				$(this).remove();
			});
			
		});
	});
	
	
	
</script>
<style type="text/css">
#dropElem {
	display: none;
	position: absolute;
	top: 0;
	border-radius: 10px 10px 10px 10px;
	box-shadow: 0 0 25px 5px #999;
	padding: 20px;
	background: #fff;
}
#shadowElem {
	position: absolute;
	top: 0;
	left: 0;
	width: 100%;
	height: 100%;
	background-color: black;
	opacity: 0.3;
}
#dropContent {
	position: relative;
}
#dropClose {
	position: absolute;
	z-index: 99999;
	cursor: pointer;
	top: -32px;
	right: -30px;
	padding: 5px;
	background-color: black;
	border-radius: 6px 6px 6px 6px;
	color: #fff;
}

</style>
</head>
<body>
	<div id="dropElem">
		<div id="dropContent">
			<div id="dropClose">X</div>
			<img src="http://beautiful-island.50webs.com/beautiful-island/beautiful-island.jpg" alt="blue" />
		</div>
	</div>
	<h3>Hello world</h3>
</body>
</html>

That’s all. Thank you for reading this.