I am hacking around with gmap3 managing to get the first task working. Showing the map using a lat long.
My javascript look likes
$('#map_canvas').gmap3(
{
action: 'init',
options: {
center: [x,y],
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControlOptions: {
mapTypeIds: []
}
}
},
{
action: 'addMarkers',
radius: 100,
markers: GetMarkers(),
clusters:
{
0:
{
content: '<div class="cluster cluster-3">CLUSTER_COUNT <div class="cluster-3text">Stops</div> </div>',
width: 66,
height: 65
}
},
marker:
{
options:
{
icon: new google.maps.MarkerImage('../img/marker.png', size, origin, null, null)
},
events:
{
mouseover: function (marker, event, data) {
getArrivalsAndStop(marker, event, data);
},
mouseout: function () {
$(this).gmap3({ action: 'clear', name: 'overlay' });
}
}
}
});
This loads the map how I want. My next step is to be able apply a new lat & long. How can I do this without destroying the whole map and recreating it everytime?
I am using jquery gmap3 plugin.
If you want to call setCenter after having initialized the map and without reloading the whole thing you can do this like this :
$('#mymap').gmap3('get').setCenter(new google.maps.LatLng(48.706685,-3.486694899999975))
$('#mymap').gmap3('get') is the magic thing here, it give you the real google map object I think.
It was hard for me to find this out so I hope it can help someone else.
From the documentation:
This example executes map.setCenter with the result of the address resolution, target is not specified because this is the map.
$('#test').gmap3(
{
action: 'getLatLng',
address: '2 bis rue saint antoine, eguilles',
callback: function(result){
if (result){
$(this).gmap3({action: 'setCenter', args:[ result[0].geometry.location ]});
} else {
alert('Bad address 2 !');
}
}
});
So it looks like if you know the coordinates and don't need to use the geocoder, it would be:
$(this).gmap3({action: 'setCenter', args:[ new google.maps.LatLng(latitude, longitude) ]});
Kind of late in the game, but I am using a list and map(google maps type). hope it helps
Here is how I achieved it
$(document).delegate('#inner_list li', 'click', function () {
var id = $(this).attr('data-id');
$("#map-canvas").gmap3({
get: {
name:"marker",
id: id,
all: true,
callback: function(objs){
$.each(objs, function(i, obj){
obj.setIcon("http://www.markericon.com");
var newLL = obj.getPosition()
$('#map-canvas').gmap3('get').panTo(newLL)
});
}
}
});
});
Related
I am trying to build a live tracking with the route using Google Map JS version in ionic 4.
What I am trying to achieve is to give the route to the user from source to destination and update the route if the user chooses a new path other than the google provided one. The source is the user and destination is some point in the map.
I am able to draw route and update it if the user change the provided path using
startNavigation(){
this.geolocation.getCurrentPosition({ enableHighAccuracy: true })
.then((position) => {
this.userPosition = position;
this.userVehicleMarker = new google.maps.Marker({
map: this.map,
position: { lat: position.coords.latitude, lng: position.coords.longitude },
icon: this.vehicleIcon
});
this.addInfoWindow(this.userVehicleMarker, 'me')
this.watchVehicle = this.geolocation.watchPosition({ enableHighAccuracy: true })
.subscribe(async (pos) =>
{
// Calling the redraw function on every 25 meters distance travelled
this.drawRouteFromVehicleToDestination(pos.coords.latitude, pos.coords.longitude)
}
}, (err: PositionError) => {
// alert(err.message)
console.log("error : " + err.message);
});
})
)
drawRouteFromVehicleToDestination(lat, lng) {
let _self = this;
let directionsService = new google.maps.DirectionsService;
let directionsRenderer = new google.maps.DirectionsRenderer({
polylineOptions: {
strokeColor: "#428BE8",
strokeWeight: 2
},
suppressMarkers: true,
preserveViewport: true
});
directionsRenderer.addListener('directions_changed', function () {
let _data = directionsRenderer.getDirections();
let _newData = _data['routes'][0]['legs'][0]
console.log(_newData)
});
directionsService.route({
origin: { lat: lat, lng: lng},
destination: { lat: 27.673586, lng: 85.435131},
travelMode: 'DRIVING',
optimizeWaypoints: true,
provideRouteAlternatives: false,
avoidTolls: true,
}, (res, status) => {
if (status == 'OK') {
directionsRenderer.setDirections(res);
directionsRenderer.setMap(this.map);
} else {
console.warn(status);
}
});
}
But the issue is, it is sending a lot of requests to google API and which does not look like a practical approach to follow.
Is there any other approach I should follow using which I could track the route and update it as per user location change and also minimize the google ping?
Thank you in advance for your help.
I think the issue is that you call drawRouteFromVehicleToDestination() very frequently (every time the vehicle position changes, from this.geolocation.watchPosition). One way to reduce the number of calls would be to "debounce" this calls, limiting them to every X ms at most, since probably it's acceptable to update every 200/300 ms. For example, you could use the lodash _.debounce function. For an in-depth explanation, see also the article Debouncing and Throttling Explained Through Examples.
this.watchVehicle = this.geolocation.watchPosition({ enableHighAccuracy: true })
.subscribe(async (pos) => {
_.debounce(() => {
this.drawRouteFromVehicleToDestination(pos.coords.latitude, pos.coords.longitude);
}, 300, { leading: true });
}, (err: PositionError) => {
// alert(err.message)
console.log("error : " + err.message);
});
Everything is working but I would really like for the last button (GPS) (sorry can't post image)
to center the map on the user location instead of just refreshing the map like I currently have it set up to do.
An example of how this would work is for the user to have the webpage open and scroll around the map, possibly changing to satellite view, then be able to click the above button (or any button for that matter) and have the map pan back to their location. Not sure if this is even possible, but I can't seem to figure it out on my own. Any help is very much appreciated. Here is the link to my Frankenstein map. http://deepfrogphoto.com/Brett-Pelletier-Photography/Links/maps/wasatch-ski-map-mobile.htm
var map, GeoMarker;
function toggleLayer(this_layer){
if(this_layer.getMap()) {
this_layer.setMap(null)
} else {
this_layer.setMap(map);}}
function initialize() {
var mapOptions = {
zoom: 20,
center: new google.maps.LatLng(40.563855, -111.675426),
mapTypeId: google.maps.MapTypeId.TERRAIN
};
map = new google.maps.Map(document.getElementById('map_canvas'),
mapOptions);
GeoMarker = new GeolocationMarker();
GeoMarker.setCircleOptions({fillColor: '#808080'});
google.maps.event.addListenerOnce(GeoMarker, 'position_changed', function() {
map.setCenter(this.getPosition());
map.fitBounds(this.getBounds());
});
google.maps.event.addListener(GeoMarker, 'geolocation_error', function(e) {
alert('There was an error obtaining your position. Message: ' + e.message);
});
GeoMarker.setMap(map);
trafficLayer = new google.maps.TrafficLayer();
trafficLayer.setMap(map);
layer1 = new google.maps.FusionTablesLayer({
map: map,
heatmap: { enabled: false },
query: {
select: "skilines",
from: "1R5pCEyNN74N8Dt9MkfNXA6A9D1HbQESzOR1fYFa7",
where: ""
},
options: {
styleId: 2,
templateId: 2
}
});
layer2 = new google.maps.FusionTablesLayer({
map: map,
heatmap: { enabled: false },
query: {
select: "resorts",
from: "19iu58FDFcBIZZ-wU1iZcf89AI5ABDJ7YTv355su5",
where: ""
},
options: {
styleId: 2,
templateId: 2
}
});
layer3 = new google.maps.FusionTablesLayer({
map: map,
heatmap: { enabled: false },
query: {
select: "summerhiking",
from: "1t1XNnG7J7Zu1p5mIUpm6qIGVYwzhkCgPy_je0IKr",
where: ""
},
options: {
styleId: 2,
templateId: 2
}
});
layer4 = new google.maps.KmlLayer('URL-to-KML.kml',
{
suppressInfoWindows: false,
map: map,
preserveViewport: true
});
}
google.maps.event.addDomListener(window, 'load', initialize);
if(!navigator.geolocation) {
alert('Your browser does not support geolocation');}
//]]>
</script>
<title>Wasatch Map by deepfrogphoto</title>
</head>
<body>
<b>Wasatch Map by deepfrogphoto -</b>
<form>
<button onclick="myFunction()">Center Map on My Location</button>
</form>
<div id="map_canvas"></div>
</body>
add a button with onclick event listener
<button onclick="myFunction()">Center</button>
then create the myFunction to center the map to user position
function myFunction(){
Map.panTo(UserCords);//UserCords = user current latitude, longitude. I suppose you have them!!!
}
EDIT
function myFunction(){
if (navigator.geolocation){
navigator.geolocation.getCurrentPosition(getPosition,showError);
}
else{
alert("Geolocation is not supported by this browser.");
}
}
function getPosition(position)
{
UserLatitude = position.coords.latitude;
UserLongitude = position.coords.longitude;
showPosition(UserLatitude, UserLongitude);
}
function showPosition(userLatitude, userLongitude){
lat= userLatitude;
lon= userLongitude;
latlon=new google.maps.LatLng(lat, lon);
YourMap.panTo(latlon);
}
function showError(error)
{
switch(error.code)
{
case error.PERMISSION_DENIED:
alert("User denied the request for Geolocation.");
break;
case error.POSITION_UNAVAILABLE:
alert("Location information is unavailable.")
break;
case error.TIMEOUT:
alert("The request to get user location timed out.")
break;
case error.UNKNOWN_ERROR:
alert("An unknown error occurred.")
break;
}
}
Hi i'm trying to show a map in my form inside a jquery dialogue,
my jquery dialogue return a partial view where i put this code inside #section scripts and i called also the maps api
<script type="text/javascript">
$(document).ready(function () {
Initialize();
});
// Where all the fun happens
function Initialize() {
// Google has tweaked their interface somewhat - this tells the api to use that new UI
google.maps.visualRefresh = true;
var Liverpool = new google.maps.LatLng(53.408841, -2.981397);
// These are options that set initial zoom level, where the map is centered globally to start, and the type of map to show
var mapOptions = {
zoom: 14,
center: Liverpool,
mapTypeId: google.maps.MapTypeId.G_NORMAL_MAP
};
// This makes the div with id "map_canvas" a google map
var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
// This shows adding a simple pin "marker" - this happens to be the Tate Gallery in Liverpool!
var myLatlng = new google.maps.LatLng(53.40091, -2.994464);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: 'Tate Gallery'
});
// You can make markers different colors... google it up!
marker.setIcon('http://maps.google.com/mapfiles/ms/icons/green-dot.png')
// a sample list of JSON encoded data of places to visit in Liverpool, UK
// you can either make up a JSON list server side, or call it from a controller using JSONResult
var data = [
{ "Id": 1, "PlaceName": "Liverpool Museum", "OpeningHours": "9-5, M-F", "GeoLong": "53.410146", "GeoLat": "-2.979919" },
{ "Id": 2, "PlaceName": "Merseyside Maritime Museum ", "OpeningHours": "9-1,2-5, M-F", "GeoLong": "53.401217", "GeoLat": "-2.993052" },
{ "Id": 3, "PlaceName": "Walker Art Gallery", "OpeningHours": "9-7, M-F", "GeoLong": "53.409839", "GeoLat": "-2.979447" },
{ "Id": 4, "PlaceName": "National Conservation Centre", "OpeningHours": "10-6, M-F", "GeoLong": "53.407511", "GeoLat": "-2.984683" }
];
// Using the JQuery "each" selector to iterate through the JSON list and drop marker pins
$.each(data, function (i, item) {
var marker = new google.maps.Marker({
'position': new google.maps.LatLng(item.GeoLong, item.GeoLat),
'map': map,
'title': item.PlaceName
});
// Make the marker-pin blue!
marker.setIcon('http://maps.google.com/mapfiles/ms/icons/blue-dot.png')
// put in some information about each json object - in this case, the opening hours.
var infowindow = new google.maps.InfoWindow({
content: "<div class='infoDiv'><h2>" + item.PlaceName + "</h2>" + "<div><h4>Opening hours: " + item.OpeningHours + "</h4></div></div>"
});
// finally hook up an "OnClick" listener to the map so it pops up out info-window when the marker-pin is clicked!
google.maps.event.addListener(marker, 'click', function () {
infowindow.open(map, marker);
});
})
}
i'm calling the map inside a div :
<div id="map_canvas" style="height: 240px; border: 1px solid gray"> map here</div>
but the problem that my map is not showing in the dialogue, even though it works well in normal page
any help plz !?
I've solved this issue with the following code:
this code is on the main view, the #next is a trigger of the form to submit, and the #dialog is inside the #form.
$(function () {
datepair();
$('#dialog').dialog({
autoOpen: false,
modal: true,
height: 720,
width: 700,
resizable: false,
title: 'Verify Location',
show: "fade",
hide: "fade",
open: function (event, ui) {
var form = $('#form');
$.ajax({
url: form.attr('actoin'),
type: form.attr('method'),
data: form.serialize(),
context: this,
success: function (result) {
$(this).html(result);
}
});
}
});
$('#next').click(function (e) {
$('#dialog').dialog('open');
return false;
});
});
this code is on the partialView
$(function () {
window.$required = $('<div></div>').dialog({
autoOpen: false,
resizable: false,
modal: true,
title: 'Verity Location Error',
buttons: {
"Ok": function () {
$(this).dialog('close');
callback();
}
}
});
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (json) {
Initialize();
}
});
return false;
});
function callback() {
$('#dialog').dialog('close');
}
function Initialize() {
//init the map
}
and this is the controller
public ActionResult PartialViewMapController()
{
return PartialView();
}
Hope it not to late for you :)
$('#map_canvas').gmap().bind('init', function(ev, map) {
if (myPosition) {
$('#map_canvas').gmap({ 'center' : myPosition });
$('#map_canvas').gmap('addMarker', { 'position': myPosition, 'bounds': true, 'icon' : '../../css/images/current_location.png'}).click( function () {
$('#map_canvas').gmap('openInfoWindow', { 'content': 'You are here!' }, this);
});
$('#map_canvas').gmap('option', 'zoom', 20);
} else {
$('#map_canvas').gmap('option', 'zoom', 8);
}
$.each(markers, function(i, marker) {
$('#map_canvas').gmap('addMarker', {
'position': new google.maps.LatLng(marker.lat, marker.lng),
'bounds': true
}).click(function() {
$('#map_canvas').gmap('openInfoWindow', { 'content': marker.name }, this);
});
});
});
I want to center and zoom to specific position. The result of this piece of code: http://postimage.org
Add the latLng of each marker to a LatLngBounds object, then use fitBounds()
Here is an example.
All in all I reached my purpose, but fitBounds() function did some mess to my expectation. My task was: create lot of makers and place them in the map. If I was use fitBounds() function my map zooms out to fit all my markers. Now how does look like my map: http://postimage.org
I am new to gmap3, is it possible to init the gmap3 using a place address?
I know generally it is done with latitude and longitude.
I have done markers with this this location name using this example.
I have already gone through this example too, but no luck.
And also i need to zoom the places on selection, i use auto complete for this purpose.
My code is given below
$('#test').gmap3(
{ action:'init',
options:{
address: "kerala,india"
}
}
);
First use getLatLng() to retrieve the location, when successfull set the center:
$('#test1').gmap3(
{ action : 'getLatLng',
address:'kerala,india',
callback : function(result){
if (result){
$(this).gmap3({action: 'setCenter', args:[ result[0].geometry.location ]},
{action: 'setZoom', args:[ 12]});
} else {
alert('not found !');
}}});
var add="kerala,india";
var geocoder = new google.maps.Geocoder();
geocoder.geocode({ address: add, region: 'no' },
function (results, status) {
if (status.toLowerCase() == 'ok') {
// Get center
var coords = new google.maps.LatLng(
results[0]['geometry']['location'].lat(),
results[0]['geometry']['location'].lng()
);
//alert(coords);
$map.gmap3("get").setCenter(coords);
$map.gmap3("get").setZoom(12);
addMarker(coords);
}
else {
alert("address not found");
}
}
function addMarker(marker) {
$map = $('#googleMap');
if (marker) {
$map.gmap3(
{ action: 'init',
options: {
center: eval(marker),
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
},
{ action: 'addMarker',
latLng: eval(marker),
options: {
draggable: true,
icon: new google.maps.MarkerImage('http://maps.google.com/mapfiles/marker.png')
},
events: {
dragend: function (mark) {
updateMarker(mark);
}
}
});
}
}
Using above code you can get latitude/longitude also and drag searched location marker.
This feature will be in next version (5.0), current is not updated,
here is a working code :
$('#test1').gmap3({
action : 'getLatLng',
address:'kerala,india',
callback : function(result){
if (result){
$(this).gmap3({
action: "init",
options:{
center: result[0].geometry.location,
zoom: 12
}
});
} else {
alert('not found !');
}
}
});
notice, if your map is already initialized, you can use in the callback
$(this).gmap3("get").setCenter(result[0].geometry.location);
$(this).gmap3("get").setZoom(12);
You can use the following code as well:
var markerData = [];
markerData.push({ address: 'kerala,india', data: '' });
$('#test').gmap3({
action: 'addMarkers',
markers: markerData
}
);