Any way to differentiate a building from a road in Google Maps? - google-maps

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.

Related

results are not the same between google places API and Google maps site

I'm working on this for 2 days and I do'nt have idea about what's happening.
I'm looking for Phamacy near an address on Google Maps
farmácia loc: R. Manoel Bandeira, 324-490, Embu - São Paulo, 06846-570, Brazil
As you can see there are a lot of pharmacies nearby 5 kilometers
When trying to do it on my site by using the google places api. The result is = NOTHING.
Follow the code
Any thoughts?
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?libraries=places&sensor=false&language=se"></script>
<script>
function init() {
const location=new google.maps.LatLng(-23.6334282, -46.8739405);
const radius = 5000;
// Make map
var mapOptions = {
center: location,
zoom: 11,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map'), mapOptions);
// Make a circle
var circOptions={
center: location,
radius: radius,
map: map
};
circle = new google.maps.Circle(circOptions);
// Get shops in radius
service = new google.maps.places.PlacesService(map);
var request={ //my request
location: location,
radius: radius,
types: ["pharmacy"]
};
service.search(request, function (results, status){
if (status == google.maps.places.PlacesServiceStatus.OK){
for (var i= 0, result; result=results[i]; i++) { //add markers
distance=google.maps.geometry.spherical.computeDistanceBetween(location, result.geometry.location);
if (distance>radius)
continue;
var marker = new google.maps.Marker({
map: map,
position: result.geometry.location,
reference: result.reference
});
}
}
});
}
google.maps.event.addDomListener(window, 'load', init);
</script>
<style>#map {height: 500px;width: 500px;}</style>
</head>
<body><div id="map"></div></body>
</html>

How to draw a path on google maps by zip code

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

Google Maps bounds on minimal zoom

I have a simple Google Map that fill the whole page.
Here is a sample:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Google Maps JavaScript API v3 Example: Marker Animations</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 stockholm = new google.maps.LatLng(59.32522, 18.07002);
var map;
function initialize() {
var mapOptions = {
zoom: 0,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: stockholm
};
map = new google.maps.Map(document.getElementById("map_canvas"),
mapOptions);
google.maps.event.addListener(map, 'idle', function() {
var b = map.getBounds();
document.getElementById("bounds").innerText = b.getSouthWest().lng() + ", " + b.getNorthEast().lng();
});
}
</script>
</head>
<body onload="initialize()">
<div id="map_canvas" style="width: 100%; height: 100%;">map div</div>
<div id="bounds" style="left: 100px; top: 0px; width: 300px; height: 30px; position: absolute; background-color: #a0a0a0;"></div>
</body>
</html>
At MINIMUM zoom level, when you can see several world maps, I expect longitude bounds to be -180 - 180, but in real I don't get it. Is my expectation wrong and why?
In real application I have a server-side code that fetches markers from database depending on current map bounds.
The bounds will report the lat and lng at the bounds of the window - even if the map has wrapped a few times. So what ever the lat,lng of the bottom right of your window will be one point, and the upper left will be the other.
I had this same issue and what I ended up doing was creating a World bounds that was 90, 180 to -90, -180 and then seeing if that fit in the window.
var ne = new google.maps.LatLng(90, 180);
var sw = new google.maps.LatLng(-90, -180)
var world = new google.maps.LatLngBounds(ne, sw);
var fetchbounds;
if(map.getBounds().contains(ne) && map.getBounds().contains(sw)){
fetchBounds = world;
}else{
fetchBounds = map.getBounds();
}

X marks along the direction

I have never worked with Google maps API.
For the school project I am working on; I need to get a direction between two locations (this is easy part and I think I can do this),
However I also need to put an X mark; at every 10 miles along the way.
Is this even possible?
Thank You.
Ok, here's a working solution that draws markers every 200 miles (I was working on big distances to check it worked on geodesic curved lines, which it does). To make this work for you, just change all the coordinates, and change 200 to 10
<!DOCTYPE html>
<html>
<head>
<title>lines with markers every x miles</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0; padding: 0 }
#map_canvas { height: 100% }
</style>
<!--- need to load the geometry library for calculating distances, see http://www.svennerberg.com/2011/04/calculating-distances-and-areas-in-google-maps-api-3/ --->
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?libraries=geometry&sensor=false"></script>
<script type="text/javascript">
function initialize() {
var startLatlng = new google.maps.LatLng(54.42838,-2.9623);
var endLatLng = new google.maps.LatLng(52.908902,49.716793);
var myOptions = {
zoom: 4,
center: new google.maps.LatLng(51.399206,18.457031),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var startMarker = new google.maps.Marker({
position: startLatlng,
map: map
});
var endMarker = new google.maps.Marker({
position: endLatLng,
map: map
});
// draw a line between the points
var line = new google.maps.Polyline({
path: [startLatlng, endLatLng],
strokeColor: "##FF0000",
strokeOpacity: 0.5,
strokeWeight: 4,
geodesic: true,
map: map
});
// what's the distance between these two markers?
var distance = google.maps.geometry.spherical.computeDistanceBetween(
startLatlng,
endLatLng
);
// 200 miles in meters
var markerDistance = 200 * 1609.344;
var drawMarkers = true;
var newLatLng = startLatlng;
// stop as soon as we've gone beyond the end point
while (drawMarkers == true) {
// what's the 'heading' between them?
var heading = google.maps.geometry.spherical.computeHeading(
newLatLng,
endLatLng
);
// get the latlng X miles from the starting point along this heading
var newLatLng = google.maps.geometry.spherical.computeOffset(
newLatLng,
markerDistance,
heading
);
// draw a marker
var newMarker = new google.maps.Marker({
position: newLatLng,
map: map
});
// calculate the distance between our new marker and the end marker
var newDistance = google.maps.geometry.spherical.computeDistanceBetween(
newLatLng,
endLatLng
);
if (newDistance <= markerDistance) {
drawMarkers = false;
}
}
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map_canvas"></div>
</body>
</html>

Get a map & street view from an adress in a PHP-variable!

I have a PHP-variable called $go_Adress which contains the adress I need to get a map and a street view from. How do I do that? I have created an api-key but else I don't know how to do it!
Hope you can help.
I have just answered another question on Google Maps, and I think I can use the same example here.
The following example may help you getting started. All you would need to do is to change the JavaScript variable userLocation with the address you have in your php variable.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Google Maps API Demo</title>
<script src="http://maps.google.com/maps?file=api&v=2&sensor=false"
type="text/javascript"></script>
</head>
<body onunload="GUnload()">
<div id="map_canvas" style="width: 400px; height: 300px"></div>
<script type="text/javascript">
var userLocation = 'London, UK';
if (GBrowserIsCompatible()) {
var geocoder = new GClientGeocoder();
geocoder.getLocations(userLocation, function (locations) {
if (locations.Placemark)
{
var north = locations.Placemark[0].ExtendedData.LatLonBox.north;
var south = locations.Placemark[0].ExtendedData.LatLonBox.south;
var east = locations.Placemark[0].ExtendedData.LatLonBox.east;
var west = locations.Placemark[0].ExtendedData.LatLonBox.west;
var bounds = new GLatLngBounds(new GLatLng(south, west),
new GLatLng(north, east));
var map = new GMap2(document.getElementById("map_canvas"));
map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
map.addOverlay(new GMarker(bounds.getCenter()));
}
});
}
</script>
</body>
</html>
The above example would render a map like the one below:
You would probably need to replace the static:
var userLocation = 'London, UK';
... with:
var userLocation = '<?php echo $go_Adress; ?>';
... as Fletcher suggested in another answer.
Note that the map will not show if the Google Client-side Geocoder cannot retreive the coordinates from the address. You may want to see how to handle this situation.
As for the API Key, you need to add it as a parameter to the <script> src that is calling the Maps API, as shown in the The "Hello, World" of Google Maps.
UPDATE:
I am updating the above example to use the Street View Panorama object. I hope that the example is self-explanatory, and that it gets you going in the right direction:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Google Maps API Demo - Street View</title>
<script src="http://maps.google.com/maps?file=api&v=2&sensor=false"
type="text/javascript"></script>
</head>
<body onunload="GUnload()">
<div id="map_canvas" style="width: 400px; height: 300px"></div>
<script type="text/javascript">
var userLocation = 'London, UK';
if (GBrowserIsCompatible()) {
var geocoder = new GClientGeocoder();
geocoder.getLocations(userLocation, function (locations) {
if (locations.Placemark)
{
var north = locations.Placemark[0].ExtendedData.LatLonBox.north;
var south = locations.Placemark[0].ExtendedData.LatLonBox.south;
var east = locations.Placemark[0].ExtendedData.LatLonBox.east;
var west = locations.Placemark[0].ExtendedData.LatLonBox.west;
var bounds = new GLatLngBounds(new GLatLng(south, west),
new GLatLng(north, east));
new GStreetviewPanorama(document.getElementById("map_canvas"),
{ latlng: bounds.getCenter() });
}
});
}
</script>
</body>
</html>
Screenshot from the above example:
2nd UPDATE:
You can enable both the street view and the map canvas, by "merging" the two examples above, as follows:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Google Maps API Demo - Street View with Map</title>
<script src="http://maps.google.com/maps?file=api&v=2&sensor=false"
type="text/javascript"></script>
</head>
<body onunload="GUnload()">
<div id="pano" style="width: 400px; height: 200px"></div>
<div id="map_canvas" style="width: 400px; height: 200px"></div>
<script type="text/javascript">
var userLocation = 'London, UK';
if (GBrowserIsCompatible()) {
var geocoder = new GClientGeocoder();
geocoder.getLocations(userLocation, function (locations) {
if (locations.Placemark)
{
var north = locations.Placemark[0].ExtendedData.LatLonBox.north;
var south = locations.Placemark[0].ExtendedData.LatLonBox.south;
var east = locations.Placemark[0].ExtendedData.LatLonBox.east;
var west = locations.Placemark[0].ExtendedData.LatLonBox.west;
var bounds = new GLatLngBounds(new GLatLng(south, west),
new GLatLng(north, east));
var map = new GMap2(document.getElementById("map_canvas"));
map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
map.addOverlay(new GMarker(bounds.getCenter()));
new GStreetviewPanorama(document.getElementById("pano"),
{ latlng: bounds.getCenter() })
}
});
}
</script>
</body>
</html>
Screenshot for street view with map:
3rd UPDATE:
The Google Maps API does not have a direct method to link the movements of the street view with the map. Therefore this has to be handled manually. The following example makes the red marker draggable, and when dropped it moves the street view accordingly. In addition, each time the street view is updated, the marker is updated on the map as well.
To try this example, make sure that you insert the API Key in the <script> src parameters, and that you try it from the domain where you registered the key. Otherwise, it looks like the events do not work properly.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Google Maps API Demo - Street View with Map</title>
<script src="http://maps.google.com/maps?file=api&v=2&sensor=false"
type="text/javascript"></script>
</head>
<body onunload="GUnload()">
<div id="pano" style="width: 400px; height: 200px"></div>
<div id="map_canvas" style="width: 400px; height: 200px"></div>
<script type="text/javascript">
var userLocation = 'Copenhagen, Denmark';
if (GBrowserIsCompatible()) {
var geocoder = new GClientGeocoder();
geocoder.getLocations(userLocation, function (locations) {
if (locations.Placemark)
{
var north = locations.Placemark[0].ExtendedData.LatLonBox.north;
var south = locations.Placemark[0].ExtendedData.LatLonBox.south;
var east = locations.Placemark[0].ExtendedData.LatLonBox.east;
var west = locations.Placemark[0].ExtendedData.LatLonBox.west;
var bounds = new GLatLngBounds(new GLatLng(south, west),
new GLatLng(north, east));
var map = new GMap2(document.getElementById("map_canvas"));
map.setCenter(bounds.getCenter(), 14);
map.addOverlay(new GStreetviewOverlay());
var marker = new GMarker(bounds.getCenter(), { draggable: true });
map.addOverlay(marker);
var streetView = new GStreetviewPanorama(document.getElementById("pano"));
streetView.setLocationAndPOV(bounds.getCenter());
GEvent.addListener(marker, "dragend", function(latlng) {
streetView.setLocationAndPOV(latlng);
});
GEvent.addListener(streetView, "initialized", function(location) {
marker.setLatLng(location.latlng);
map.panTo(location.latlng);
});
}
});
}
</script>
</body>
</html>
Screenshot of the above example:
Getting the street view working nicely with the map could be the topic of another Stack Overflow question, as there are quite a few considerations to make.
You will need to include a javascript file which uses the GClientGeocoder object as in this example:
http://code.google.com/apis/maps/documentation/services.html#Geocoding_Object
The javascript will need to be passed through a PHP interpreter which injects the address into a javascript variable.
So, for the above example
var myAddress = '<?php echo $go_Adress; ?>';
showAddress(myAddress);
But first I recommend getting a very basic map shown.
http://code.google.com/apis/maps/documentation/introduction.html