Google Maps v3 API Extend Bounds. Javascript How-To? - javascript

function initialize(){
// Creating a map
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 10,
center: new google.maps.LatLng(53.0123601276819, -2.44519164333635),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var m = [];
function addMarker(title, lat, lng) {
m[m.length] = new google.maps.Marker({
position: new google.maps.LatLng(lat, lng),
map: map,
title: title,
clickable: true,
icon: 'http://domain.com/MVC/images/full.png'
});
}
addMarker('Home', 53.0682143712504, -2.52150736731894);
addMarker('Away', 53.0123601276819, -2.44519164333635);
addMarker('Away', 59.0123601276819, -2.44519164333635);
// Create a LatLngBounds object
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < m.length; i++) {
// Insert code to add marker to map here
// Extend the LatLngBound object
bounds.extend(m[i]);
}
alert(m[0]);
map.fitBounds(bounds);
document.write(getBounds());
}
The above is my code.
My intentions are to develop a map which shows numerous markers and pans the zoom such that all the markers fit on my screen.
I am new to JS.
My understanding is that
var m = [];
creates an empty array.
Then everytime i call addMarker() the details get added to this array m
At the top I set a default zoom and center point.
I then add various markers.
I then loop through each key in the m array and extend the bounds using the data from this.
It is then my understanding that map.fitBounds(bounds); should redefine the zoom/center as applicable to fit all the markers.
It does not.
All my markers show, but the zoom/center is not auto adjusting as such, and I have no idea why.
Any advice would be greatly appreciated.
Thanks

You need to pass a LatLng object to the bounds.extend function.
Here is the code :
....
bounds.extend(new google.maps.LatLng(lat, lng));
....

Here is a clarification of the above answer which is correct except it's missing a parenthesis and a little brief.
//make an empty bounds variable
var bounds = new google.maps.LatLngBounds();
//do your map stuff here
//special note: make sure your lat and lng are floats or googleMaps will error
var lat = 38.103;
var lng = -121.572;
bounds.extend(new google.maps.LatLng(lat, lng));
//adjust the viewport of the map
//special note: this only needs to be done once, don't put it in a loop
map.fitBounds(bounds);

Related

setView not defined with bing API

Im trying to change the mapview while using Bing maps API. I have my map initialized already but im trying to change the map view to center in on a pin who's location i have. Im merely trying to get the view to move using setView but im unsure how to move it.
function findpin() {
console.log("hello3");
var pin;
//loop through and find searched pin object
for (var i = 0; i < allPins.length; i++) {
if (searchbox.value == allPins[i].entity.title) {
pin = allPins[i];
break;
}
};
console.log(pin);
//set pin
pinSelected(pin);
//var locs = [array of Microsoft.Maps.Location];
//var rect = Microsoft.Maps.LocationRect.fromLocations(locs);
map = setView({
mapTypeId: Microsoft.Maps.MapTypeId.aerial,
center:new Microsoft.Maps.Location(0, 0),
zoom:100,
});
console.log("hello5");
}
Assuming that you initialized the map by:
var map = new Microsoft.Maps.Map(document.getElementById('myMap'), {});
Then you can use the setView on the instantiated map to update the view:
map.setView({
mapTypeId: Microsoft.Maps.MapTypeId.aerial,
center: new Microsoft.Maps.Location(0, 0),
zoom: 20
});
Notice that the max zoom level is 20.

How to pull user's current location and display on google map api? [duplicate]

This question already has answers here:
JavaScript Google Maps API How to Store Location lat/long to Global Variable
(2 answers)
Closed 5 years ago.
So two things I am trying to accomplish
1) to pull the user's current location
2) then to display it on a google map
from my research, I see that I can use the following to get the user's currention location
navigator.geolocation.getCurrentPosition(success);
function success(pos) {
var crd = pos.coords;
console.log('Your current position is:');
console.log(`Latitude : ${crd.latitude}`);
console.log(`Longitude: ${crd.longitude}`);
console.log(`More or less ${crd.accuracy} meters.`);
};
and the following to initiate a google map
function initMap() {
var uluru = {lat: -25.363, lng: 131.044};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: uluru
});
var marker = new google.maps.Marker({
position: uluru,
map: map
});
}
so the problem I am having is how can I accomplish both at the same time?
I have tried to put the second function inside the first function, but that doesn't work ...
thank you all for your help in advance !
initMap needs to know what the location is. Currently, you're setting the position to "uluru" inside initMap; instead, try passing the coordinates into the function, and then pulling the coordinates off of that object (you could just reuse the object, but you'd have to account for the fact that the fields are called longitude/latitude in the first case and lng/lat on the second). Something like this:
navigator.geolocation.getCurrentPosition(success);
function success(pos) {
var crd = pos.coords;
console.log('Your current position is:');
console.log(`Latitude : ${crd.latitude}`);
console.log(`Longitude: ${crd.longitude}`);
console.log(`More or less ${crd.accuracy} meters.`);
initMap(crd);
};
function initMap(coordinates) {
var location = {'lng': coordinates.longitude, 'lat': coordinates.latitude};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: location
});
var marker = new google.maps.Marker({
position: location,
map: map
});
}

Center a boundary of polygons in Google Maps

I am trying to find a better way to center my google map.
I've already written code to add in Markers to Outline and area squarely of which is being store in an array: Coords[i], in-which when returning to the map after save, it centers the map window based on the "first marker" lat/lng coordinates Coords[0].
I am trying to figure out a better way to center the map where there is adequate space around my outline area.
I've try doing it on Dragend, which works somewhat:
google.maps.event.addListener(this.map, 'dragend', function(mapEvent) {
var lat = mapEvent.getCenter() .lat(),
lng = mapEvent.getCenter() .lng(),
console.log(lat + " " + lng + " " + this);
});
But it keeps throwing an error saying:
"Unable to get property 'getCenter' of undefined or null reference"
Can someone tell me what I am doing wrong OR tell be a better way to achieve what I'm trying to do?
As, another option
It would be nice if possible if I can keep the first marker [0] the centering marker as it is already, But don't allow it to outline... just the markers 1 + and on .... But I don't know how to modify my code to do that.
Just looking for a solution that works.
My complete Code is here:
http://pastiebin.com/embed/593d6d809e2f0
You can use a LatLngBounds object. Loop through your Polygons if you have more than one and extend your bounds object with each path coordinates.
LatLngBounds
You can then make your map fit the bounds object so it will zoom and center accordingly by using map.fitBounds().
fitBounds
If you use multi-paths Polygon, make sure you use getPaths method instead of getPath as in the code below.
function initialize() {
var mapOptions = {
zoom: 4,
center: new google.maps.LatLng(0, 0),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
var polygon = new google.maps.Polygon({
editable: true,
strokeOpacity: 0,
strokeWeight: 0,
fillColor: '#00FF00',
fillOpacity: .6,
paths: [
new google.maps.LatLng(39, 4),
new google.maps.LatLng(34, 24),
new google.maps.LatLng(43, 24),
new google.maps.LatLng(39, 4)],
map: map
});
// Create the bounds object
var bounds = new google.maps.LatLngBounds();
// Get paths from polygon and set event listeners for each path separately
polygon.getPath().forEach(function (path, index) {
bounds.extend(path);
});
// Fit Polygon path bounds
map.fitBounds(bounds);
}
initialize();
#map-canvas {
height: 200px;
}
<div id="map-canvas"></div>
<script src="https://maps.googleapis.com/maps/api/js"></script>
Ok I just figured out a way!
I simply grabbed the lat/lng coordinates of the center of the polygon drawn and centered my whole map with that.
var bounds = new google.maps.LatLngBounds();
var i;
//Get Center of Saved Coordinates of the drawn polygons
for (var i = 0; i < values["coords"].length; i++) {
bounds.extend(values["coords"][i]);
}
var movemaplat = bounds.getCenter().lat();
var movemaplng= bounds.getCenter().lng();
console.log("MY MAP CENTER " + movemaplat + ", " + movemaplng);
Thanks to #Daniel Vassallo's answer here: How to get the center of a polygon in google maps v3?

Measuring distance between two points using google api

I'm trying to measure the distance between a marker and a point that has been searched for by postcode. The idea is to make markers appear within a certain radius. as far as I can tell I've done it right but clearly not.
The current code for the function looks like this:
function setup_map(latitude, longitude) {
var _position = new google.maps.LatLng(latitude, longitude);
var mapOptions = {
zoom: 14,
center: _position
}
var map = new google.maps.Map(document.getElementById('map'), mapOptions);
#foreach (var i in ViewData.Model)
{
<text>
var markerPos = {lat: #i.Lat, lng:#i.Long}
var distance = google.maps.geometry.spherical.computeDistanceBetween(markerPos, _position);
var marker = new google.maps.Marker
({
position: new google.maps.LatLng (markerPos),
map: map,
title: "" + (#i.id),
});
</text>
}
}
This function reloads the map and all the markers on it. At the minute I'm not too concerned with loading the markers within the radius. I just want to load them all.
When you click the search button, the map loads to the postcode entered but doesn't load any markers. If I remove the "var distance" line, it still goes to the postcode and loads all of the markers. So by process of elimination, there must be something wrong with this line but I have no idea what.

Google map load more than 1000 markers browser not responding

I am new to Google maps, I am plotting the gps data onto a Google map, it works fine up to 500 points. If the data exceeds more than 500 it slows down is there any alternate way to plot markers onto a map.
I am just marking the gps data in Google map on certain time period.
Later I need to plot hundreds of thousands of gps data in Google map,below method slows down and exit the firefox or chrome (it times out).
How to plot more data on google map and also it should be fast
My javascript code, sale data will be of json data:
function show_map_all_data(sale_data)
{
init_map();
var count_actual=sale_data.length;
var locations=[];
for (var i=0;i<count_actual;i++)
{
var temp=[]
temp.push(sale_data[i]['GPS_latitude'],sale_data[i]['GPS_longitude'])
locations.push(temp);
}
//console.log(locations);
var infowindow = new google.maps.InfoWindow();
var marker, i;
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][0], locations[i][1]),
icon: {
path: google.maps.SymbolPath.CIRCLE,
strokeColor: '#8e2014',
scale: 4,
strokeOpacity: 1.0,
strokeWeight: 10,
fillColor: '#8e2014',
animation: google.maps.Animation.DROP,
},
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations[i][0] + "," + locations[i][1]);
infowindow.open(map, marker);
}
})(marker, i));
}
}
You'll likely need to look into markerclustering in order to speed up your page load times (and avoid time out). Multiple markers rendered on the client side is probably the downfall of many mapping applications performance wise. It is difficult to benchmark, fix and in some cases even establish there is an issue (due to browser implementation differences, hardware available to the client, mobile devices, the list goes on).
The simplest way to begin to address this issue is to use a marker clustering solution. The basic idea is to group geographically similar locations into a group with the number of points displayed. As the user zooms into the map these groups expand to reveal individual markers beneath.
Perhaps the simplest to implement is the markerclusterer library. A basic implementation would be as follows (after library imports, and not reflective of your code, this is just the simplest example I could come up with):
<script type="text/javascript">
function initialize() {
var center = new google.maps.LatLng(37.4419, -122.1419);
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 3,
center: center,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var markers = [];
for (var i = 0; i < 100; i++) {
var location = yourData.location[i];
var latLng = new google.maps.LatLng(location.latitude,
location.longitude);
var marker = new google.maps.Marker({
position: latLng
});
markers.push(marker);
}
var markerCluster = new MarkerClusterer(map, markers);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
The markers instead of being added directly to the map are added to an array. This array is then passed to the library which handles complex calculation for you and attached to the map.
Not only do these implementations massively increase client side performance but they also in many cases lead to a simpler and less cluttered UI and easier digestion of data on larger scales.
Other implementations are available from Google.
Edit to answer comment
If you look here: http://gmaps-utility-library.googlecode.com/svn/trunk/markerclusterer/1.0/docs/reference.html and look for a property called maxZoom you can set a zoom level in the clusterer options object after which the clustering will be turned off to allow all markers to be plotted.

Categories