I want to show a path map and distance between to points by zip code or city name l ike we enter to and from place and map will generate between them , total distance between them will be calculated.
You can do this in three steps
1) generate map by post city or zip code
create map1.php
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no"/>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Google Maps JavaScript API v3 Example:Post City or Zip</title>
</head>
<body >
<form action="map2.php" method="post" >
Enter 1st zip code / city <input type="text" name="input1" id="input1"><br/>
Enter 2nd zip code / city <input type="text" name="input2" id="input2">
<input type="submit">
</form>
</body>
</html>
2) Create map2.php and generate map
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no"/>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Google Maps JavaScript API v3 Example: Directions Simple</title>
<link href="http://code.google.com/apis/maps/documentation/javascript/examples/default.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var directionDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer();
var chicago = new google.maps.LatLng(41.850033, -87.6500523);
var myOptions = {
zoom:7,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: chicago
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
directionsDisplay.setMap(map);
}
function calcRoute() {
var start = '<?php echo $_POST['input1']; ?>';
var end = '<?php echo $_POST['input2']; ?>';
var request = {
origin:start,
destination:end,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
</script>
</head>
<body onLoad="initialize(),calcRoute()">
<?php
// calculate laglong by address and zip code
function getLatLong($address){
if (!is_string($address))die("All Addresses must be passed as a string");
$_url = sprintf('http://maps.google.com/maps?output=js&q=%s',rawurlencode($address));
$_result = false;
if($_result = file_get_contents($_url)) {
if(strpos($_result,'errortips') > 1 || strpos($_result,'Did you mean:') !== false) return false;
preg_match('!center:\s*{lat:\s*(-?\d+\.\d+),lng:\s*(-?\d+\.\d+)}!U', $_result, $_match);
$_coords['lat'] = $_match[1];
$_coords['long'] = $_match[2];
}
return $_coords;
}
$to = getLatLong($_POST['input1']);echo "<br/>";print_r($to);
$from = getLatLong($_POST['input2']);echo "<br/>";print_r($from);
echo distance($to['lat'], $to['long'], $from['lat'], $from['long'], "m") . " miles";
// // calculate distance by lat long
function distance($lat1, $lon1, $lat2, $lon2, $unit) {
$theta = $lon1 - $lon2;
$dist = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) + cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta));
$dist = acos($dist);
$dist = rad2deg($dist);
$miles = $dist * 60 * 1.1515;
$unit = strtoupper($unit);
if ($unit == "K") {
return ($miles * 1.609344);
} else if ($unit == "N") {
return ($miles * 0.8684);
} else {
return $miles;
}
}
?>
<div id="map_canvas" style="top:30px;"></div>
</body>
</html>
that generate map and getLatLong() function find laglong and distance function find distance between city or zip code
Firstly you have to find geolocation of your zipcode which you can find it easily using gmaps api. Then use "distanceTo" method to find distance between to points (your geopoint and zip code generated geopoint) . distanceTo method gives you distance in meters.
Check this post
Related
i am try to google load map which get map from address for that i try below code but it not work for me please find out my mistake.
<html>
<head>
<script src="http://maps.google.com/maps/api/js?libraries=places®ion=uk&language=en&sensor=true"></script>
<script type="text/javascript">
var geocoder;
var map;
function codeAddress() {
geocoder = new google.maps.Geocoder();
var lat = '';
var lng = '';
var city_state_zip ='390002';
var street_address = 'vadodara';
var address = street_address + " " + city_state_zip;
geocoder.geocode({ 'address': address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
lat = results[0].geometry.location.lat(); //getting the lat
lng = results[0].geometry.location.lng(); //getting the lng
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
var latlng = new google.maps.LatLng(lat, lng);
var myOptions = {
zoom: 8,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
}
window.onload = function () {
codeAddress();
}
</script>
</head>
<body>
<div id="map_canvas" style="height: 350px; width: 500px; margin: 0.6em;">
</div>
</body>
</html>
in that there i add location manual which is '390002 vadodara'.
See the Google Maps API here
What you want to do is send an AJAX request like the following:
http://maps.googleapis.com/maps/api/geocode/json?sensor=false&address=vadodara+390002
This will return latitude and longitude coordinates for you to plot on the map
Here is a complete solution, the RTN_address.php function is below.
This will return a map that has a marker on the address specified.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="X-UA-Compatible" content="IE=8" / >
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>Simple Map</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<style>
html, body, #map-canvas {
height: 300px;
width: 840px;
margin: 0px;
padding: 0px
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script>
function show_map_from_sql_address(id) {
var url_with_ID = "RTN_address.php?id=" + id.toString();
$.ajax({
type : "GET",
url : url_with_ID,
data : "pid=A5843",
dataType : "json",
success : function(data) {
var geocoder = new google.maps.Geocoder();
var address = data.foo;
var map;
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 latlng = new google.maps.LatLng(latitude, longitude);
var mapOptions = {
zoom : 10,
center : latlng,
mapTypeId : google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map : map,
position : results[0].geometry.location
});
}
});
}
});
};
</script>
</head>
<body onload="show_map_from_sql_address(7)">
<div id="map-canvas"></div>
</body>
</html>
RTN_address.php
<?php
$id = $_GET['id'];
$query1 = "SELECT * FROM table_of_homes WHERE id ='" . $id . "';";
$result1 = mysql_query($query1);
$address = "Not_set";
if (!$result1) {
die('Invalid query: ' . mysql_error());
} else {
$fields = array();
while ($row1 = mysql_fetch_array($result1, MYSQL_ASSOC)) {
$Street_Address = $row1['Street_Address'];
$City_Town = $row1['City_Town'];
$State = $row1['State']`enter code here`;
$Zipcode = $row1['Zipcode'];
$address = $Street_Address ." ". $City_Town ." ". $State .", ". $Zipcode;
}
}
//NOTE: you can test this by entering an address here.
//$address = "111 Oak Hill Avenue Kingston PA, 18760";
echo json_encode(array('foo' => $address ));
?>
I want to provide a feature like user will provide a city,state and country. Then my aim is to mark the location provided by the user on the google maps.
My code is:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="generator" content="CoffeeCup HTML Editor (www.coffeecup.com)">
<meta name="dcterms.created" content="Tue, 08 Jan 2013 05:31:17 GMT">
<meta name="description" content="">
<meta name="keywords" content="">
<title></title>
<?php
// get and breakdown the results then store them in $var's
$Address = "99999 parkplace, new york, NY";
$urladdress = urlencode($Address);
$Base_url = "http://maps.google.com/maps/geo?q=";
$urlParts = "&output=xml";
$urlrequest = $Base_url . $urladdress . $urlParts;
$xml = simplexml_load_file($urlrequest);
$num = "0";
$value=$xml->Response->Placemark;
$GeoFindAdd{$num} = $value->address;
$GeoFindCords{$num} = $value->Point->coordinates;
?>
<script
src="http://maps.googleapis.com/maps/api/js?key=AIzaSyDY0kkJiTPVd2U7aTOAwhc9ySH6oHxOIYM&sensor=false">
</script>
<script>
var myCenter=new google.maps.LatLng(<?php echo $GeoFindCords{$num}; ?>);
function initialize()
{
var mapProp = {
center:myCenter,
zoom:5,
mapTypeId:google.maps.MapTypeId.ROADMAP
};
var map=new google.maps.Map(document.getElementById("googleMap"),mapProp);
var marker=new google.maps.Marker({
position:myCenter,
});
marker.setMap(map);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="googleMap" style="width:500px;height:380px;"></div>
</body>
</html>
The output of the code is
http://wfs-01.wapka.mobi/300030/300030787_6850a0ae9a.png
Is there something wrong i am doing? Or any other way to mark the location by providing location.
Thanks.
I got the answer
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="generator" content="CoffeeCup HTML Editor (www.coffeecup.com)">
<meta name="dcterms.created" content="Tue, 08 Jan 2013 05:31:17 GMT">
<meta name="description" content="">
<meta name="keywords" content="">
<title></title>
<script
src="http://maps.googleapis.com/maps/api/js?key=AIzaSyDY0kkJiTPVd2U7aTOAwhc9ySH6oHxOIYM&sensor=false">
</script>
<script>
var geocoder, map;
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(10, 10);
var myOptions = {
zoom: 0,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
codeAddress();
}
function codeAddress() {
var address = "Kottayam, Kerala";
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
}
else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
</script>
</head>
<body onload="initialize()">
<div id="map_canvas" style="width: 320px; height: 480px;"></div>
</body>
</html>
I have a MySQL db that I convert to XML on the fly for querying a RouteBoxer page. I began all of these pages from Google examples. So, in order to get my XML, I have:
<?php
require("phpsqlajax_dbinfo.php");
// Get parameters from URL
$center_lat = $_GET["lat"];
$center_lng = $_GET["lng"];
$radius = $_GET["radius"];
// Start XML file, create parent node
$dom = new DOMDocument("1.0");
$node = $dom->createElement("markers");
$parnode = $dom->appendChild($node);
// Opens a connection to a mySQL server
$connection=mysql_connect ($hostname_DB2, $username_DB2, $password_DB2);
if (!$connection) {
die("Not connected : " . mysql_error());
}
// Set the active mySQL database
$db_selected = mysql_select_db($database_DB2, $connection);
if (!$db_selected) {
die ("Can\'t use db : " . mysql_error());
}
// Search the rows in the markers table
$query = sprintf("SELECT id, address, name, lat, lng, type FROM markers");
$result = mysql_query($query);
if (!$result) {
die("Invalid query: " . mysql_error());
}
header("Content-type: text/xml");
// Iterate through the rows, adding XML nodes for each
while ($row = #mysql_fetch_assoc($result)){
$node = $dom->createElement("marker");
$newnode = $parnode->appendChild($node);
$newnode->setAttribute("name", $row['name']);
$newnode->setAttribute("address", $row['address']);
$newnode->setAttribute("lat", $row['lat']);
$newnode->setAttribute("lng", $row['lng']);
$newnode->setAttribute("id", $row['id']);
}
echo $dom->saveXML();
?>
Similarly, my RouteBoxer code looks like this:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>Google Maps JavaScript API Search Along a Route Example</title>
<script src="http://maps.google.com/maps/api/js?sensor=false" type="text/javascript"></script>
<script src="/Test/Domain/src/RouteBoxer.js" type="text/javascript"></script>
<script type="text/javascript">
var map = null;
var boxpolys = null;
var directions = null;
var routeBoxer = null;
var markers = [];
var infoWindow;
var locationSelect;
var distance = null; // km
function initialize() {
// Default the map view to the UK.
var mapOptions = {
center: new google.maps.LatLng(54.219218, -2.905669),
mapTypeId: google.maps.MapTypeId.ROADMAP,
zoom: 6
};
map = new google.maps.Map(document.getElementById("map"), mapOptions);
routeBoxer = new RouteBoxer();
directionService = new google.maps.DirectionsService();
directionsRenderer = new google.maps.DirectionsRenderer({ map: map });
}
function route() {
// Clear any previous route boxes from the map
clearBoxes();
// Convert the distance to box around the route from miles to km
distance = parseFloat(document.getElementById("distance").value) * 1.609344;
var request = {
origin: document.getElementById("from").value,
destination: document.getElementById("to").value,
travelMode: google.maps.DirectionsTravelMode.DRIVING
}
// Make the directions request
directionService.route(request, function(result, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsRenderer.setDirections(result);
// Box around the overview path of the first route
var path = result.routes[0].overview_path;
var boxes = routeBoxer.box(path, distance);
drawBoxes(boxes);
} else {
alert("Directions query failed: " + status);
}
});
}
// Draw the array of boxes as polylines on the map
function drawBoxes(boxes) {
boxpolys = new Array(boxes.length);
for (var i = 0; i < boxes.length; i++) {
boxpolys[i] = new google.maps.Rectangle({
bounds: boxes[i],
fillOpacity: 0,
strokeOpacity: 1.0,
strokeColor: '#000000',
strokeWeight: 1,
map: map
//Perform Search
});
}
}
// Clear boxes currently on the map
function clearBoxes() {
if (boxpolys != null) {
for (var i = 0; i < boxpolys.length; i++) {
boxpolys[i].setMap(null);
}
}
boxpolys = null;
}
</script>
<style>
#map {
border: 1px solid black;
}
</style>
</head>
<body onload="initialize();">
<div id="map" style="width: 800px; height: 600px;"></div>
Box within at least <input type="text" id="distance" value="5" size="2">miles
of the route from <input type="text" id="from" value="tacoma"/>
to <input type="text" id="to" value="seattle"/>
<input type="submit" onclick="route()"/>
</body>
</html>
So how do I get my items to apepar within the routeboxer? How can I send the bounds of the routeboxer to the xml to query? Or, looking at it from the other way around, how do i get my RouteBoxer to query the XML and return only the items within the bounds?
I'm very confused!
For the simplicity sake I have put the code for displaying the map and the route in the function "initialize". The Map IS getting displayed, but the route is not. Please point out the error.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>Google Maps JavaScript API Example</title>
<script src="http://maps.google.com/maps/api/js?sensor=false" type="text/javascript"></script>
<script type="text/javascript">
var map;
var latlng = new google.maps.LatLng (-34.397, 150.644);
var directionsDisplay = new google.maps.DirectionsRenderer ();;
var directionsService = new google.maps.DirectionsService ();
function initialize ()
{
var myOptions =
{
zoom:8,
center:latlng,
mapTypeId:google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map (document.getElementById ("map"), myOptions);
directionsDisplay.setMap (map);
var initialPoint = latlng;
var latlng2 = new google.maps.LatLng (-34.400, 150.744);
var pointAfterDragging = latlng2;
var start = initialPoint;
var end = pointAfterDragging;
var request = {
origin:start,
destination:end,
travelMode:google.maps.TravelMode.DRIVING
};
directionsService.route (request,
function (result, status)
{
if (status == google.maps.DirectionsStatus.OK)
{
directionsDisplay.setDirections (result);
}
});
}
</script>
</head>
<body onload="initialize()" onunload="GUnload()" topmargin="0" leftmargin="0">
<div id="map" style="width: 341px; height: 271px"></div>
<div id="directionsPanel" style="float:right;width:30%;height 100%"></div>
</body>
</html>
You have two problems.
First there is no method defined called GUnload.
Second, the directions you are trying to get returns ZERO_RESULTS. You can always try to alert status to see whether it returns any directions. If it doesn't nothing will be shown.
You should try with some other locations instead and it should be fine. You can also pass it addresses instead of latlng's if you want to try that instead :)
To alert the status you could do this:
directionsService.route (request,
function (result, status)
{
alert(status);
if (status == google.maps.DirectionsStatus.OK)
{
directionsDisplay.setDirections (result);
}
});
}
So if I have a general GPS Lat/Lng point, would it be possible to say, yes this point is in a building, or this point is on a road which a car could travel on?
I do not think you can determine if a point is a road or a building purely with Google Maps data. To do this I think you would need some additional data source.
However, you may be able to determine if a point is a road by using the Snap point to street technique.
I have re-written the technique to use Google Maps API v3 and added the Haversine function to tell you the distance (in km) between the original clicked point and the corresponding point in the nearest street.
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no"/>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Google Maps JavaScript API v3 Example: Directions Simple</title>
<link href="http://code.google.com/apis/maps/documentation/javascript/examples/default.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
rad = function(x) {return x*Math.PI/180;}
distHaversine = function(p1, p2) {
var R = 6371; // earth's mean radius in km
var dLat = rad(p2.lat() - p1.lat());
var dLong = rad(p2.lng() - p1.lng());
var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(rad(p1.lat())) * Math.cos(rad(p2.lat())) * Math.sin(dLong/2) * Math.sin(dLong/2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
var d = R * c;
return d.toFixed(3);
}
var dirn = new google.maps.DirectionsService();
var map;
function initialize() {
var center = new google.maps.LatLng(53.7877, -2.9832);
var myOptions = {
zoom:15,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: center
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
google.maps.event.addListener(map, "click", function(event) {
// == When the user clicks on a the map, get directiobns from that point to itself ==
var request = {
origin: event.latLng,
destination: event.latLng,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
dirn.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
if(response.routes && response.routes.length > 0){
route = response.routes[0];
if(route.overview_path && route.overview_path.length > 0){
pos = route.overview_path[0];
new google.maps.Marker({
position: pos,
map: map
});
alert(distHaversine(request.origin, pos));
}
}
}
});
});
}
</script>
</head>
<body onload="initialize()">
<div id="map_canvas"></div>
</body>
</html>
I hope this is helpful.
Best place to ask is https://gis.stackexchange.com/. Isn't it possible to figure out the road location from the layer which contains the roads? You'll be given the lat-long's of all road nodes. Unless it's a curved line, you can find if your lat-long point lies on the road line. To convert lat-long to cartesian, follow the link.