Center and auto zoom google map - maps

;)
I'm a not so familiar with the Google Maps API yet but I was able to figure out most questions a beginners faults. ;) But what I don't get is to center the map between the two markers I set and to auto zoom it... ;(
Maybe someone has the right hint for me...
Thanks and cheers!
<script> function initialize() {
var myLatLng = new google.maps.LatLng(0, 0);
var mapOptions = {
zoom: 3,
mapTypeControl: false,
navigationControl: false,
scrollwheel: false,
streetViewControl: false,
zoomControl: false,
center: myLatLng,
mapTypeId: google.maps.MapTypeId.TERRAIN
};
var map = new google.maps.Map(document.getElementById('map'), mapOptions);
var flightPlanCoordinates = [
new google.maps.LatLng(100, 100),
new google.maps.LatLng(120, 120)
];
var lineSymbol = {
path: google.maps.SymbolPath.FORWARD_CLOSED_ARROW
};
var flightPath = new google.maps.Polyline({
path: flightPlanCoordinates,
geodesic: true,
strokeColor: '#FF0000',
strokeOpacity: 0.5,
icons: [{
icon: lineSymbol,
offset: '100%'
}],
strokeWeight: 2
});
flightPath.setMap(map);
}
google.maps.event.addDomListener(window, 'load', initialize);</script>
<div id="map" style="width: 100%; height: 300px"></div>
<script>jQuery('#myModal-<? the_ID(); ?>').on('shown', function () {
google.maps.event.trigger(map, 'resize');
map.setCenter(new google.maps.LatLng(42.3605336, -72.6362989));
})</script>

You need to fit the bounds of the map as it pertains to your markers.
// Make an array of the LatLng's of the markers you want to show
var LatLngList = new Array (new google.maps.LatLng (52.537,-2.061), new google.maps.LatLng (52.564,-2.017));
// Create a new viewpoint bound
var bounds = new google.maps.LatLngBounds ();
// Go through each...
for (var i = 0, LtLgLen = LatLngList.length; i < LtLgLen; i++) {
// And increase the bounds to take this point
bounds.extend (LatLngList[i]);
}
// Fit these bounds to the map
map.fitBounds (bounds);

// Make an array of the LatLng's of the markers you want to show
var LatLngList = new Array (
new google.maps.LatLng(<?php echo esc_html( $et_location_lat ); ?>, <?php echo esc_html( $et_location_lng ); ?>),
new google.maps.LatLng(<?php echo esc_html( $destination_lat ); ?>, <?php echo esc_html( $destination_lng ); ?>)
);
// Create a new viewpoint bound
var bounds = new google.maps.LatLngBounds ();
// Go through each...
for (var i = 0, LtLgLen = LatLngList.length; i < LtLgLen; i++) {
// And increase the bounds to take this point
bounds.extend (LatLngList[i]);
}
// Fit these bounds to the map
map.fitBounds (bounds);
As I open the map within a modal box I've to reload the bounced map as soon as I open it:
jQuery('#myModal-<? the_ID(); ?>').on('shown', function () {
google.maps.event.trigger(map, 'resize');
map.fitBounds (bounds);
})

Related

How do I update marker position via geometry, with a smooth transition?

I'm currently on a ReactJS+Nodejs application, trying to integrate OpenLayers. What I need is to change the GPS position of a marker, in real-time (via socket.io).
So far, I've come up with this code:
this.map = new Map({
target: "map",
layers: [
new TileLayer({
source: new XYZ({
attributions: 'Tiles © ArcGIS',
url: 'https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}'
})
}),
],
view: new View({
center: fromLonLat([-8.455826, 40.168307]),
rotation: 1.1344640138,
easing: 0.5
})
});
var vectorSource = new VectorSource({});
var markersLayer = new VectorLayer({
source: vectorSource,
});
this.map.addLayer(markersLayer);
var point1 = new Point(
fromLonLat([-8.455826, 40.168307])
);
var point2 = new Point(
fromLonLat([-8.456819, 40.166388])
);
var marker = new Feature({
geometry: point1,
name: "My point",
});
vectorSource.addFeature(marker);
var style = new Style({
image: new CircleStyle({
radius: 7,
fill: new Fill({color: 'black'}),
stroke: new Stroke({
color: 'white', width: 2
})
})
});
marker.setStyle(style);
setTimeout(function () {
marker.setGeometry(point2);
marker.getGeometry().translate(40, -40);
}, 3500);
The marker moves, however the transition occurs in an instant. Is there a way to make it move like a "CSS linear transition" to give it a more realistic look?
Using a timer you could split the move into steps along the line between the old and new positions, e.g. for 100 10ms steps
var line = new LineString([oldCoordinates, newCoordinates])];
var step = 0;
var key = setInterval( function() {
if (step < 100) {
step++;
marker.setGeometry(new Point(line.getCoordinateAt(step/100)));
} else {
clearInterval(key);
}
}, 10);
You might also be able to base something on the flight animation example https://openlayers.org/en/latest/examples/flight-animation.html

How to get dynamic place from google map marker in angularJS

In my app using google place map predefined location but i need location name lat and lng from google map dynamically when moves the marker on google
Im using angularJs 1.5
my code like this
$scope.Markers =
{
"lat": '12.976154',
"lng": '77.445760',
}
//Setting the Map options.
$scope.MapOptions = {
center: new google.maps.LatLng($scope.Markers.lat, $scope.Markers.lng),
zoom: 7,
rotation: 45,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
//Initializing the InfoWindow, Map and LatLngBounds objects.
$scope.InfoWindow = new google.maps.InfoWindow();
$scope.Latlngbounds = new google.maps.LatLngBounds();
$scope.Map = new google.maps.Map(document.getElementById("dvMap"), $scope.MapOptions);
//Looping through the Array and adding Markers.
// for (var i = 0; i < $scope.Markers.length; i++) {
// var data = $scope.Markers[i];
var myLatlng = new google.maps.LatLng($scope.Markers.lat, $scope.Markers.lng);
//Initializing the Marker object.
var marker = new google.maps.Marker({
position: myLatlng,
map: $scope.Map,
title: $scope.Markers.title
});
//Adding InfoWindow to the Marker.
(function (marker, data) {
google.maps.event.addListener(marker, "click", function (e) {
// $scope.InfoWindow.setContent("<div style = 'width:100px;min-height:40px'>" + data.description + "</div>");
// $scope.InfoWindow.open($scope.Map, marker);
});
})(marker, $scope.Markers);
//Plotting the Marker on the Map.
$scope.Latlngbounds.extend(marker.position);
// }
//Adjusting the Map for best display.
$scope.Map.setCenter($scope.Latlngbounds.getCenter());
$scope.Map.fitBounds ($scope.Latlngbounds);
Please help me
You can attach the drag & dragend events to the google maps markers using 'google.maps.event.addListener' method.
function getMarkerCoords(markerobj){
google.maps.event.addListener(markerobj, 'dragend', function(evt){
infoWindow.setOptions({
content: '<p>Marker Current Lat: ' + evt.latLng.lat().toFixed(3) + ' Current Lng: ' + evt.latLng.lng().toFixed(3) + '</p>'
});
infoWindow.open(map, markerobj);
});
google.maps.event.addListener(markerobj, 'drag', function(evt){
console.log("marker is being dragged");
});
}

Marker Clusterer in DevExtreme Mobile

I'm developing an application in DevExtreme Mobile. In application, I use DXMap in this application. How can I use the marker clusterer structure in DevExtreme Mobile App?
You can use Google Maps Marker Clusterer API to create and manage per-zoom-level clusters for a large number of DevExtreme dxMap markers. Here is an example:
 dxMap Marker Clusterer
This example is based on the approach described in the Google Too Many Markers! article
Here is sample code:
$("#dxMap").dxMap({
zoom: 3,
width: "100%",
height: 800,
onReady: function (s) {
var map = s.originalMap;
var markers = [];
for (var i = 0; i < 100; i++) {
var dataPhoto = data.photos[i];
var latLng = new google.maps.LatLng(dataPhoto.latitude, dataPhoto.longitude);
var marker = new google.maps.Marker({
position: latLng
});
markers.push(marker);
}
var markerCluster = new MarkerClusterer(map, markers);
}
});
The kry is to use the google maps api. I did it for my app, here how.
This the html, very simple:
<div data-options="dxView : { name: 'map', title: 'Punti vendita', pane: 'master', secure:true } ">
<div data-bind="dxCommand: { id: 'back', behavior: 'back', type: 'back', visible: false }"></div>
<div data-options="dxContent : { targetPlaceholder: 'content' } ">
<div style="width: 100%; height: 100%;">
<div data-bind="dxMap:options"></div> <!--this for the map-->
<div id="large-indicator" data-bind="dxLoadIndicator: {height: 60,width: 60}" style="display:inline;z-index:99;" />
<div data-bind="dxPopover: {
width: 200,
height: 'auto',
visible: visible,
}">
</div>
</div>
</div>
</div>
When the page loads, the app read the gps coordinates:
function handleViewShown() {
navigator.geolocation.getCurrentPosition(onSuccess, onError, options);
jQuery("#large-indicator").css("display", "none"); //this is just a gif to indicate the user to wait the end of the operation
}
If the gps location is correctly read, I save the coordinates (the center of the map):
function onSuccess(position) {
var lat1 = position.coords.latitude;
var lon1 = position.coords.longitude;
center([lat1, lon1]);
}
And these are the options I set to my dxMap:
options: {
showControls: true,
key: { google: "myGoogleApiKey" },
center: center,
width: "100%",
height: "100%",
zoom: zoom,
provider: "google",
mapType: "satellite",
autoAdjust: false,
onReady: function (s) {
LoadPoints();
var map = s.originalMap;
var markers = [];
for (var i = 0; i < MyPoints().length; i++) {
var data = MyPoints()[i];
var latLng = new google.maps.LatLng(data.location[0], data.location[1]);
var marker = createMarker(latLng, data.title, map, data.idimp);
markers.push(marker);
}
var markerCluster = new MarkerClusterer(map, markers, { imagePath: 'images/m' });
}
},
Where MyPoints is populated calling LoadPoints:
function LoadPoints() {
$.ajax({
type: "POST",
async:false,
contentType: "application/json",
dataType: "json",
url: myApiUrl,
success: function (Response) {
var tempArray = [];
for (var point in Response) {
var location = [Response[p]["latitudine"], Response[p]["longitudine"]];
var title = Response[p]["name"] + " - " + Response[p]["city"];
var temp = { title: title, location: location, tooltip: title, onClick: GoToNavigator, idpoint: Response[p]["id"] };
tempArray.push(temp);
}
MyPoints(tempArray);
},
error: function (Response) {
jQuery("#large-indicator").css("display", "none");
var mex = Response["responseText"];
DevExpress.ui.notify(mex, "error");
}
});
}
Note that in the folder Myproject.Mobile/images I included the images m1.png, m2.png, m3.png, m4.png and m5.png.
You can found them here.

Fit zoom to show all markers. I already set center correctly

I have a map with several markers and I need to fit them all to the window. I'm using Mobile Angular UI: http://mobileangularui.com/ and Angular Google Maps: http://angular-ui.github.io/angular-google-maps/#!/
I define map with default center and zoom:
$scope.map = {
center: { // set on XXX as initial default
latitude: 45.322594,
longitude: -2.938249
},
zoom: 14,
options: mapServices.getMapOptions().mapOptions
};
When I add markers to the map y extend bounds:
var markers = [];
var bounds = new google.maps.LatLngBounds();
for loop ....
var marker = {
latitude: indicadores[i].sensores[j].lat, //43.401188,
longitude: indicadores[i].sensores[j].lon, //-5.823359,
title: indicadores[i].sensores[j].nombre,
valor: getValor(indicadores[i], indicadores[i].sensores[j].ultimo_valor, indicadores[i].sensores[j].ultimo_estado),
url: "#/sensor/" + $scope.$parent.Despliegue.id + "/"+ indicadores[i].id + "/" + indicadores[i].sensores[j].id,
id: i,
fit: true,
options: {
icon: { url: obtenerImagen(indicadores[i].factor_ambiental, indicadores[i].sensores[j].ultimo_estado) }
},
showWindow: false,
};
var latlng = new google.maps.LatLng(marker.latitude, marker.longitude);
bounds.extend(latlng);
markers.push(marker);
And then I get center and apply bounds:
var centro = bounds.getCenter();
$scope.map.center = {
latitude: centro.lat(),
longitude: centro.lng()
}
var sw = bounds.getSouthWest();
var ne = bounds.getNorthEast();
$scope.map.bounds = {
northeast: {
latitude: ne.lat(),
longitude: ne.lng()
},
southwest: {
latitude: sw.lat(),
longitude: sw.lng()
}
}
I'm having the map perfectly centered but it doesn't zoom to fit all markers.
Any help, please? Thanks in advance!
Try to use in tag <ui-gmap-markers> fit option fit="'true'" in your template file
<ui-gmap-markers idKey="map.dynamicMarkers.id" models="map.dynamicMarkers" coords="'self'"
fit="'true'">

Google Maps API Tooltip

<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true"></script>
<script src="js/jquery.gmap.js"></script>
<script type="text/javascript">
$('#myModal').modal('show');
function initialize() {
var mapOptions = {
controls: {
panControl: true,
zoomControl: true,
mapTypeControl: true,
scaleControl: true,
streetViewControl: true,
overviewMapControl: true
},
scrollwheel: false,
zoom: 6,
center: new google.maps.LatLng(-23, -44)
}
var map = new google.maps.Map(document.getElementById('googlemaps'), mapOptions);
setMarkers(map, affiliates);
}
var affiliates = [
['São Paulo', -23.544778, -46.640443],
['Curitiba', -25.430424, -49.267594, 5],
['Porto Alegre', -30.029993, -51.228282, 3],
['Ribeirão Preto', -21.175955, -47.810941, 2],
['Limeira', -22.564294, -47.404107, 1],
['Rio de Janeiro', -22.901542, -43.180402, 1]
];
function setMarkers(map, locations) {
var image = {
url: 'images/boneco_base.png',
size: new google.maps.Size(22, 30),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(0, 32)
};
var shape = {
coords: [1, 1, 1, 20, 18, 20, 18, 1],
type: 'poly'
};
for (var i = 0; i < locations.length; i++) {
var affiliate = locations[i];
var myLatLng = new google.maps.LatLng(affiliate[1], affiliate[2]);
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
icon: image,
shape: shape,
title: affiliate[0],
zIndex: affiliate[3]
});
}
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
i have the code above to show my affiliates, but i want when the user clicks on image show a tooltip where it show more details.
i already tried to put some codes inside for but it doesn't work for me
how can i do it ?
<script src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
//$('#myModal').modal('show');
var map;
var infoWindow = new google.maps.InfoWindow(), marker, i;
var bounds = new google.maps.LatLngBounds();
function initialize() {
var mapOptions = {
controls: {
panControl: true,
zoomControl: true,
mapTypeControl: true,
scaleControl: true,
streetViewControl: true,
overviewMapControl: true
},
scrollwheel: false
}
map = new google.maps.Map(document.getElementById('googlemaps'), mapOptions);
setMarkers(map, affiliates);
}
var affiliates = [
['São Paulo', -23.544778, -46.640443, "(11) 3594-3666<br>R. Barão de Itapetininga, 140 - República<br>CEP: 01042-000<br>São Paulo - SP"],
['Curitiba', -25.430424, -49.267594, "(41) 3029-0501<br>R. Mal. Deodoro, 503 cj 1802 - Centro<br>CEP: 80020-320<br>Curitiba - PR"],
['Porto Alegre', -30.029993, -51.228282, "(51) 3023-4224<br>R. dos Andradas, 1234 cj 1202 - Centro Histórico<br>CEP: 90020-008<br>Porto Alegre - RS"],
['Ribeirão Preto', -21.175955, -47.810941, "(16) 3633-1221<br>R. Álvares Cabral, 576 cj 31 - Centro<br>CEP: 14010-080<br>Ribeirão Preto - SP"],
['Limeira', -22.564294, -47.404107, "(19) 3441-5474<br>R. Santa Cruz, 787 cj 82 - Centro<br>CEP: 13480-041<br>Limeira - SP"],
['Rio de Janeiro', -22.901542, -43.180402, "(21) 2516-2565<br>Av. Pres. Vargas, 482 cj 2012 - Centro<br>CEP: 20071-004<br>Rio de Janeiro - RJ"]
];
function setMarkers(map, locations) {
var image = {
url: 'images/boneco_base.png',
size: new google.maps.Size(22, 30),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(0, 32)
};
for (var i = 0; i < locations.length; i++) {
var myLatLng = new google.maps.LatLng(locations[i][1], locations[i][2]);
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
icon: image,
title: locations[i][0]
});
bounds.extend(marker.position);
google.maps.event.addListener(marker, 'click', (function (marker, i) {
return function () {
infoWindow.setContent("<strong>" + locations[i][0] + "</strong><br>" + locations[i][3] + "<br><br><a href='#' onclick='var latLng = new google.maps.LatLng("+locations[i][1]+", "+locations[i][2]+");map.setZoom(17); map.panTo(latLng);'>[+] Ampliar</a><br><a href='#' onclick='map.setZoom(6); map.fitBounds(bounds);infoWindow.close();'>[-] Reduzir</a>");
infoWindow.open(map, marker);
}
})(marker, i));
}
map.fitBounds(bounds);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>

Resources