Wednesday, June 5, 2013

Add google map in html page

index.html

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title></title>
<link rel="stylesheet" href="styles.css" />
<!--[if lt IE 9]>
<script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
</head>
<body>

<div id="canvas"></div>
<br />
<label for="latitude">Latitude:</label>
<input id="latitude" type="text" value="" />
<label for="longitude">Longitude:</label>
<input id="longitude" type="text" value="" />

<script type="text/javascript" src="gmap.js"></script>

</body>
</html>

gmap.js


// configuration
var myZoom = 12;
var myMarkerIsDraggable = true;
var myCoordsLenght = 6;
var defaultLat = 37.973787;
var defaultLng = 23.722426;

// creates the map
// zooms
// centers the map
// sets the map's type 
var map = new google.maps.Map(document.getElementById('canvas'), {
zoom: myZoom,
center: new google.maps.LatLng(defaultLat, defaultLng),
mapTypeId: google.maps.MapTypeId.ROADMAP
});

// creates a draggable marker to the given coords
var myMarker = new google.maps.Marker({
position: new google.maps.LatLng(defaultLat, defaultLng),
draggable: myMarkerIsDraggable
});

// adds a listener to the marker
// gets the coords when drag event ends
// then updates the input with the new coords
google.maps.event.addListener(myMarker, 'dragend', function(evt){
document.getElementById('latitude').value = evt.latLng.lat().toFixed(myCoordsLenght);
document.getElementById('longitude').value = evt.latLng.lng().toFixed(myCoordsLenght);
});

// centers the map on markers coords
map.setCenter(myMarker.position);

// adds the marker on the map

myMarker.setMap(map);


styles.css

#canvas {
    width: 600px;
    height: 400px;

}


No comments:

Post a Comment