check position change in google map - javascript

I am using cordova in building the google map for device platform.
What I am going to ask is that, how to check if the user position is change?
Because the scenario is, when user is away from the specified place, the page will be redirected to logout page.
Here is the working map I have for static map (with no position change yet)
var longitude = position.coords.longitude;
var latitude = position.coords.latitude;
var latLong = new google.maps.LatLng(latitude, longitude);
var mapOptions = {
center: latLong,
zoom: 18,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
var marker = new google.maps.Marker({
position: latLong,
map: map,
title: 'my location'
});
So the function to achieve what I want is more or less like this:
var positionMust = x, -y;
if (latLong != positionMust )
{
window.location.href//to logout
}
We need to check this everytime user is moving away.
Can anybody help? Many many thanks in advance.

You can use navigator.geolocation API as exemplified in this post:
Accessing a Google Maps API on pageload with Angular
In particular are of your interest navigator.geolocation.getCurrentPosition() and navigator.geolocation.watchPosition().
and it's also possible to check if a position is within a certain region using Google Geometry Library, see:
Determine if location is within a certain region in Google Map
All the geolocation APIs above mentioned are implemented on devices by the cordova-plugin-geolocation.

Related

Google Places API autocomplete performance becomes progressively slower

I have a webpage that uses the google places and google maps API on the same page. A user selects a certain location from google places autocomplete and the google map then centers on that given place.
The logic of this event seems to work fine, however I've noticed that 1.) 'autocomplete' place suggestions become slower and slower with each additional place searched through the search bar, and 2.) the shadow on the place suggestions becomes darker and darker with each additional search (see pictures below).
This problem seems to be 'reset' once the browser cache is cleared, leading me to believe the issue is that the previous search terms in the input box are being stored somewhere and slowing down the google places performance.
I apologize if this is a simple issue, but googling the past few days on this problem has turned up nothing for me. Any help??
View of the search box before any problems:
Search bar after multiple previous searches:
My initMap() function:
function initMap() {
var myLatLng = {lat: 40, lng: -20}; //display the initial main map
map = new google.maps.Map(document.getElementById('bigMainMap'), {
center: myLatLng,
mapTypeControl: false,
zoom: 3
});
var searchTerm = $('#mainAdvSearchBox')[0];
var autoComplete = new google.maps.places.Autocomplete(searchTerm);
var geocoder = new google.maps.Geocoder();
geocoder.geocode( {'address': chosenArea}, function(results, status) { //use google place bounds to appropriately zoom on street/city/country
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
map.fitBounds(results[0].geometry.viewport);
google.maps.event.addListenerOnce(map, 'bounds_changed', setSelectedMarkers);
}
else
setAllMarkers(); //user has directly navigated to adventures page, show world map and all events
});
}
My tag for including the google apis:
<script src="https://maps.googleapis.com/maps/api/js?key=MYKEY&libraries=places&callback=initMap" async defer></script>
This issue is caused by a mistake in implementation. This normally happens when
new google.maps.places.Autocomplete
is added inside the input's keyup event listener like this:
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -33.8688, lng: 151.2195},
zoom: 13
});
var input = document.getElementById('pac-input');
// this is where things starts to go wrong
input.addEventListener('keyup', function() {
var autocomplete = new google.maps.places.Autocomplete(input);
});
}
Check out the wrong implementation here: http://jsbin.com/popucap/edit?js,output
The listener part for the input box is unnecessary. This will make your autocomplete go insane. The autocomplete will pile itself on the previous suggestions again and again. because every time you input a character, the autocomplete is being created again.
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -33.8688, lng: 151.2195},
zoom: 13
});
var input = document.getElementById('pac-input');
// this is how it should be
var autocomplete = new google.maps.places.Autocomplete(input);
}
Check out the working sample here: http://jsbin.com/cubirod/edit?js,output
If this is not how you're doing it, you should get an idea of how this happens with my samples. Hope it helps!

Meteor templates loading

I've build a simple app with Meteor. It basicly gets locations from database and shows them to user. This is done via webservice. In the template I have a google map. Which gets the coordinates of locations and then displays them on the map. The basic idea works. However, the problem is that my webservice is called when google map loads. Therefore when template map is created (it's created when user selects tab /map and map template is created - or am I wrong?). And because of that when I open my homepage first, the webservice is not called and I don't get the data.
How is this problem solved? I want to load all the data when user opens the app. onRendered and onCreated won't solve this I think. If you know the answer please write it down, if it is obvious please share a link where I can read about it.
Thanks
To solve your issue, you should first create the map (without marker), and when you have the geolocalisation of the user, you will be able to draw it on the map. Or you can wait the user position before rendering the map. All you need is a reactive treatment.
You can store a variable in a ReactiveVar - you just need to add this very interesting package :
meteor add reactive-var
or you can use the meteor Session. I will use the session for the example, it's easier.
Your template.js (that I wrote without testing, comment on this post if you have any issue)
Template.map.onRendered(function() {
// Create an undefined value for this template,
this.marker;
var myLatLng = {lat: -25.363, lng: 131.044};
// Render an empty map
this.map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: myLatLng
});
// Each time a reactive variable like ReactiveVar or session is edited,
// rerun this function
this.autorun(function() {
// this autorun will rerun each time Session.get("userPosition") is edited
var userPosition = Session.get("userPosition");
if (userPosition && this.marker === undefined) {
this.marker = new google.maps.Marker({
position: myLatLng,
map: this.map,
title: 'Hello user!'
});
}
});
});
Source google map API : https://developers.google.com/maps/documentation/javascript/examples/marker-simple

Add marker to existing google map (without refresh google map) [duplicate]

This question already has answers here:
Google maps api V3 - Adding multiple markers dynamically from query results
(2 answers)
Closed 7 years ago.
I have a google map on my website (in production) with few markers, i would like to know if its possible to add a marker on an existing map without refresh my google map.
This what i have:
I load my webpage, google map appears with markers
On click on a button, i would like to add one marker on my map (without refresh my page or the google map)
I can realize this with refresh my google map but i think that its better to do this without refresh due to limitation of google map display per day.
This is my code:
<button onclick="addMarker()">Add marker</button>
<script>
function addMarker(){
var myLatLng = new google.maps.LatLng(44, 6);
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
});
}
</script>
var latlng = new google.maps.LatLng(42.745334, 12.738430);
function addmarker(latilongi) {
var marker = new google.maps.Marker({
position: latilongi,
title: 'new marker',
draggable: true,
map: map
});
map.setCenter(marker.getPosition())
}
$('#btnaddmarker').on('click', function() {
addmarker(latlng)
})
Yes. When you added your markers originally, your probably did something like:
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: 'Hello World!'
});
The map already existed (map: map), and you added markers. You can do the same thing later to add more markers.

JS Function undefined when it is clearly a prototype of the object I am using

I am using GoogleMaps JS API V3 with ClusterMarker. So far so good, I have a working map with customised clusters.
I decided I needed a method to open the infoWindow with some information of the clicked cluster, including some anchored links.
I did some searching on SO and Google and came up with something along these lines from this StackOverflow answer.
var infoWindow = new google.maps.InfoWindow();
google.maps.event.addListener(markerCluster, 'clusterclick', function (clickedCluster) {
console.log(clickedCluster);
var center = clickedCluster.getCenter();
var latLng = new google.maps.LatLng(center);
// infowindow.setContent("Info Window");
// infowindow.setPosition(latLng);
// infowindow.open(map);
});
In the console.log(clickedCluster) I'm given a Cluster object that has 6 methods, and a load of properties. One of these functions is getCenter() that returns the 'Center of the cluster icon that has been clicked'.
When I uncomment this line: var center = clickedCluster.getCenter(); I get an error saying that getCenter() is not a function.
Can anyone help me shed some light on what I'm doing wrong here please?
Thanks in advance
So the solution to the problem turned out to be that clickedCluster was returned as an array. The below works great.
var infoWindow = new google.maps.InfoWindow();
google.maps.event.addListener(markerCluster, 'clusterclick', function (clickedCluster) {
var center = clickedCluster[0].getCenter();
var latLng = new google.maps.LatLng(center.lat(),center.lng());
infoWindow.setContent(getDailyDeals(center.lat(),center.lng()));
infoWindow.setPosition(latLng);
infoWindow.open(map);
});

Google Maps API using jQuery Plugin: How to get a marker's latitude and longitude on click?

I am using a plugin for Google Maps API V3. I use it to put a marker on the map and allow the user to drag the marker to a spot on the map. I want to get the lat,lng of the marker on click.
goMap Plugin Page:
http://www.pittss.lv/jquery/gomap/index.php
This function that sets up the marker in the first place.
$("#map").goMap({
zoom: 16,
maptype: 'ROADMAP',
navigationControl: false,
mapTypeControl: false,
scrollwheel: true,
disableDoubleClickZoom: false,
markers: [{
draggable:true,
latitude: data.lat,
longitude: data.lng,
icon:'./images/pink.png'
}]
});
I tried calling the native getLat() method on goMap(), but I don't think I was doing that right. Any help is much appreciated.
After a bit of sleuthing, it looks like it uses jQuery's data() function to bind data to the map. You can get to the data through $('#map').data(), which has information on markers.
Each marker has an id, and you can get the marker's id through the array $.goMap.markers. Note that $.goMap.markers only contains strings that are IDs and not the markers themselves.
You'll need to use that array to find the id you want (or you might know it ahead of time) and then call $('#map').data()['MARKER_ID'] to get the marker object. The marker has a few properties, including title, visible, icon, id, and position.
We care about position, which has two properties, wa and ya. wa seems to be latitude, while ya seems to be longitude. So $('#map').data()['MARKER_ID'].position.wa will get you the latitude, for example. It seems some markers have a latitude and longitude property, not sure why that's not always there (from my brief testing at least), but you could try $('#map').data()['MARKER_ID'].latitude instead.
Hope this helps.
I don't know why, but the props names changing often with the time... Seems like the best solution is get the key names and use to know the lat & lng.
So, if you want to get the coords after a drag, for example, you'll use:
$.goMap.createListener({type:'marker', marker:'MARKER_ID'}, 'dragend', function() {
var i_prop = 2;
var map_data_marker = $('#map').data()['MARKER_ID'].position;
var map_data_marker_keys = [];
for (var key in map_data_marker)
{
if (i_prop--)
{
if (map_data_marker.hasOwnProperty(key))
{
map_data_marker_keys.push(key);
}
}
else
{
break;
}
}
var lat_lng = map_data_marker[map_data_marker_keys[0]] + ', ' + map_data_marker[map_data_marker_keys[1]];
});

Categories

Resources