Google Maps bounds on minimal zoom - google-maps

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();
}

Related

How can I know the scale that my Google maps is currently in? [duplicate]

I have a Google map (v3) on my site and I want to know what scale is my current zoom. The thing is that the user can change it's zoom so the scale can change.
The information I need is the actual width in kilometers of my map. I know I can use Bounds... but is there any other way? I really don't want to use Bounds.
Thank you!
So you can call map.getBounds(). Then you can use functions on the google.maps.geometry.spherical class like computeDistanceBetween or computeLength. Something like this I think should give you what you need:
<!DOCTYPE html>
<html>
<head>
<title></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>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false&libraries=geometry"></script>
<script type="text/javascript">
function initialize() {
var homeLatlng = new google.maps.LatLng(51.476706,0); // London
var myOptions = {
zoom: 15,
center: homeLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
google.maps.event.addListener(map, 'bounds_changed', function() {
// find out the map's bounds:
var bounds = map.getBounds();
// from that, get the coordinates for the NE and SW corners
var NE = bounds.getNorthEast();
var SW = bounds.getSouthWest();
// from that, figure out the latitudes and the longitudes
var lat1 = NE.lat();
var lat2 = SW.lat();
var lng1 = NE.lng();
var lng2 = SW.lng();
// construct new LatLngs using the coordinates for the horizontal distance between lng1 and lng2
var horizontalLatLng1 = new google.maps.LatLng(lat1,lng1);
var horizontalLatLng2 = new google.maps.LatLng(lat1,lng2);
// construct new LatLngs using the coordinates for the vertical distance between lat1 and lat2
var verticalLatLng1 = new google.maps.LatLng(lat1,lng1);
var verticalLatLng2 = new google.maps.LatLng(lat2,lng1);
// work out the distance horizontally
var horizontal = google.maps.geometry.spherical.computeDistanceBetween(horizontalLatLng1,horizontalLatLng2);
// work out the distance vertically
var vertical = google.maps.geometry.spherical.computeDistanceBetween(verticalLatLng1,verticalLatLng2);
// round to kilometres to 1dp
var horizontalkm = convertMetresToKm(horizontal);
var verticalkm = convertMetresToKm(vertical);
alert(horizontalkm + ' km horizontal, ' + verticalkm + ' km vertical');
});
}
function convertMetresToKm(metres) {
return Math.round(metres / 1000 *10)/10; // distance in km rounded to 1dp
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map_canvas"></div>
</body>
</html>

Google map two drop menus produce two markers on map

I have made some code to plot basic markers on a google map selectable via a dropdown.
however : I'd like to have two drop downs with the same options in them, and only display the markers selected in the dropdown (i.e. have 100+ markers but only show 2). Id also like to 'draw a line' in-between the two points and have a pop up window (as per google maps does) when hovering over the location. Lastly, can the window resize to the markers?
Here's what I've got so far:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0px; padding: 0px }
#map_canvas { height: 100% }
</style>
<script type="text/javascript" src="https://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
// Here you can specify all list of your geolocation options
window.markers = {
'Moscow': {lat: 55.74257, lng: 37.61547},
'Saint Petersburg': {lat: 59.93952, lng: 30.31202}
};
// This is a initialization of map and set of all markers
function initialize() {
var latlng = new google.maps.LatLng(window.markers['Moscow'].lat, window.markers['Moscow'].lng);
var myOptions = {
zoom: 5,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
window.map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
for(i in window.markers){
var marker = new google.maps.Marker({
position: new google.maps.LatLng(window.markers[i].lat, window.markers[i].lng),
map: map
});
}
}
// This is a handler for dropdown change
function mychange(element){
var city = new google.maps.LatLng(window.markers[element.value].lat, window.markers[element.value].lng);
map.setCenter(city);
return false;
}
</script>
</head>
<body onload="initialize()">
// This is your dropdown
<select onchange='mychange(this)'>
<option value='Moscow'>Moscow
<option value='Saint Petersburg'>Saint Petersburg
</select>
// This DIV for you map
<div id="map_canvas" style="width:100%; height:100%"></div>
</body>
</html>

navigation that pans to markers on a saved google map

I've been looking through the google api and I've been having trouble finding info on how you would make marker navigation. For example http://maps.google.com/maps/ms?msid=214364913744716823698.00046c8f8a60625db2c21&msa=0&ll=48.068903,-91.109619&spn=0.537763,0.883026
I've made this map with three markers, I'd like to embed this into mysite and then have three links that match up with the markers, and when you click the link it pans the map to that maker. Is it possible to do this using a saved google map?
Here is a complete example. Basically, the map.setCenter command will allow you to move from one point to another
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Demo</title>
<script src="http://maps.google.com/maps/api/js?sensor=false"
type="text/javascript"></script>
</head>
<body>
<div>
Point A
Point B
Point C
</div>
<div id="map" style="width: 640px; height: 480px;"></div>
<script type="text/javascript">
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 9,
center: new google.maps.LatLng(40.00, -104.00),
mapTypeId: google.maps.MapTypeId.TERRAIN
});
var a = new google.maps.LatLng(40.00, -104.00);
var b = new google.maps.LatLng(41.00, -105.00);
var c = new google.maps.LatLng(39.00, -103.00);
new google.maps.Marker({
position: a,
map: map
});
new google.maps.Marker({
position: b,
map: map
});
new google.maps.Marker({
position: c,
map: map
});
</script>
</body>
</html>

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