I have this set of codes and it works, however everytime I click on my button to get my current location, it will position my map to center. Is it possible to get my location WHILE not moving my map?
google.maps.event.addDomListener(controlText, 'click', function(self)
{
getLocation(self);
});
function getLocation(self)
{
console.log("in get location", self);
let locationOptions =
{
timeout : 60000,
enableHighAccuracy : true
};
navigator.geolocation.getCurrentPosition
(
(position) =>
{
self.curLat = position.coords.latitude;
self.curLong = position.coords.longitude;
console.log("updated position coord:"+self.curLat+","+self.curLong);
self.local = new Storage(LocalStorage);
self.local.set("currLong", self.curLong);
self.local.set("currLat", self.curLat);
map.setCenter(new google.maps.LatLng(self.curLat, self.curLong));
markers = removeMarker(markers);
addMarker(map, markers);
},
(error) => {console.log(error);}, locationOptions
);
};
myLocationMarker = new google.maps.Marker
({
map : map,
icon : image,
animation : google.maps.Animation.DROP,
position : map.getCenter(),
id : 'myLocationMarker'
});
markers.push(myLocationMarker);
I have solve my issue by changing
map.setCenter(new google.maps.LatLng(self.curLat, self.curLong));
to
var latLng = new google.maps.LatLng(self.curLat, self.curLong);
and passing the data to addMarker to use it for position.
Remove this line:
map.setCenter(new google.maps.LatLng(self.curLat, self.curLong));
Related
I have a Google Map with a set of markers on. I'm trying to add MarkerClusterer to it to simplify the view. Overall, doing so should be pretty easy from what I've seen online but when I try it, my map doesn't show any markers, clusters or anything. My code is below:
function calculateCenter() {
center = map.getCenter()
}
let center
let worldCenter = new window.google.maps.LatLng(32.249974, 5.800781)
let mapOptions = {
center: worldCenter,
zoom: 3,
scrollwheel: false
}
let map = new google.maps.Map(document.querySelector('.banner--map--parks'), mapOptions)
let infoWindow = new google.maps.InfoWindow()
let markers = []
map.addListener('idle', _ => {
calculateCenter()
})
fetch('/api/parks.json')
.then(response => response.json())
.then(data => {
data.forEach(park => {
if (park.lat && park.lng) {
let title = park.name
let position = new google.maps.LatLng(park.lat, park.lng)
let icon = 'https://raw.githubusercontent.com/Concept211/Google-Maps-Markers/master/images/marker_blue.png'
let marker = new google.maps.Marker({
position: position
title: title,
icon: icon,
// map: map
})
let parkIWContent = '<div class="iw">' + park.name + '</div>'
marker.addListener('click', (function(marker, parkIWContent) {
return function() {
infoWindow.setContent(parkIWContent);
infoWindow.open(map, marker);
// map.panTo(new google.maps.LatLng(park.lat, park.lng))
};
})(marker, parkIWContent))
markers.push(marker)
}
})
})
console.log(markers)
let markerCluster = new MarkerClusterer(map, markers)
map.addListener("click", _ => {
infoWindow.close()
})
As you can see, at one point I did output the array of markers and they do all show up in the console but still fail to show on the map.
Can anyone spot any issues with the code that may be causing this?
Thanks
I've actually managed to solve this. I needed to move the Marker Clusterer inside the .then in order for it to work.
Hi I am using Google maps alongside algolia where I have an index 'locations' with 'lat' and 'lng'.
I am getting user location and watching position, I am also displaying markers from database based on lng and lat however I want to add a bit to it:
So I have followed that link:
https://www.algolia.com/doc/guides/geo-search/geo-search-overview/
And came up with:
#extends('master') #section('title', 'Live Oldham')
#section('extrafiles')
<script type="text/javascript" src="https://maps.google.com/maps/api/js?v=3&key=AIzaSyAirYgs4Xnt9QabG9v56jsIcCNfNZazq50&language=en"></script>
<script type="text/javascript" src="{!! asset('js/homesearch.js') !!}"></script>
#endsection
#section('content')
<div id="map_canvas" style="height:600px;"></div>
#endsection
and js:
$(document).ready(function() {
var map;
function initializeMap(){
map = new google.maps.Map(document.getElementById('map_canvas'), {
zoom: 19,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
}
function locError(error) {
// the current position could not be located
alert("The current position could not be found!");
}
function setCurrentPosition(position) {
currentPositionMarker = new google.maps.Marker({
map: map,
position: new google.maps.LatLng(
position.coords.latitude,
position.coords.longitude
),
title: "Current Position"
});
map.panTo(new google.maps.LatLng(
position.coords.latitude,
position.coords.longitude
));
}
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
console.log(latitude);
console.log(longitude);
function displayAndWatch(position) {
// set current position
setCurrentPosition(position);
// watch position
watchCurrentPosition(position);
console.log(position);
}
function watchCurrentPosition(position) {
var positionTimer = navigator.geolocation.watchPosition(
function (position) {
setMarkerPosition(
currentPositionMarker,
position,
)
});
}
function setMarkerPosition(marker, position) {
marker.setPosition(
new google.maps.LatLng(
position.coords.latitude,
position.coords.longitude)
);
}
function initLocationProcedure() {
initializeMap();
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(displayAndWatch, locError);
}else{
alert("Your browser does not support the Geolocation API");
}
}
$(document).ready(function() {
initLocationProcedure();
});
var APPLICATION_ID = '75RQSC1OHE';
var SEARCH_ONLY_API_KEY = 'f2f1e9bba4d7390fc61523a04685cf12';
var INDEX_NAME = 'locations';
var PARAMS = { hitsPerPage: 100 };
// Client + Helper initialization
var algolia = algoliasearch(APPLICATION_ID, SEARCH_ONLY_API_KEY);
var algoliaHelper = algoliasearchHelper(algolia, INDEX_NAME, PARAMS);
// Map initialization
var markers = [];
//alert("heelo");
var fitMapToMarkersAutomatically = true;
algoliaHelper.on('result', function(content) {
renderHits(content);
var i;
// Add the markers to the map
for (i = 0; i < content.hits.length; ++i) {
var hit = content.hits[i];
console.log(hit)
var marker = new google.maps.Marker({
position: {lat: hit.longitude, lng: hit.latitude},
map: map,
title: hit.slug
});
markers.push(marker);
}
// Automatically fit the map zoom and position to see the markers
if (fitMapToMarkersAutomatically) {
var mapBounds = new google.maps.LatLngBounds();
for (i = 0; i < markers.length; i++) {
mapBounds.extend(markers[i].getPosition());
}
map.fitBounds(mapBounds);
}
});
function renderHits(content) {
$('#container').html(JSON.stringify(content, null, 2));
}
algoliaHelper.setQueryParameter('aroundRadius', 5000).search(); // 5km Radius
});
However there are few problems with this that I don't know how to tackle:
When user is moving, it doesn't center the map on the marker.
At this moment marker jumps between location when user moves, I would like for the marker to dynamically move on the map when user moves.
I want to use algolia to dynamically set markers, so I want to show markers with 5km radius from user location, and dynamically add or remove markers that are outside it.
I can't help you much with those questions since it's mostly about how to use GMap JS lib and I'm not experienced with it. However, something else catched my eyes:
var marker = new google.maps.Marker({
position: {lat: hit.longitude, lng: hit.latitude},
map: map,
title: hit.slug
});
You should put your coordinates in the _geoloc field in order to be able to use the geo-search features. It looks like this:
_geoloc: {
lat: 40.639751,
lng: -73.778925
}
I am new to Sencha Touch, knows Javascript,jQuery,HTML5.
I am developing simple Google Map application with Sencha Touch + Sencha Architect where it place marker on current position and also use Google Place to find 'store'(i.e. types need for Google place search) near the current location. I am getting the locations in 'callbackPlaces' (i.e. latitude, longitude) but Google.Maps.Marker gives error in 'callbackPlaces' method (i.e. called through 'addMarker' method and I also tried and tested by putting Google.Maps.Marker in 'callbackPlaces').
Ext.define('MyApp.view.Map', {
extend: 'Ext.Map',
alias: 'widget.map',
config: {
useCurrentLocation: true,
listeners: [
{
fn: 'onMapMaprender',
event: 'maprender'
}
]
},
onMapMaprender: function(map, gmap, options) {
this.initializePlaces();
},
initializePlaces: function() {
//Set Marker on Current Position
var geo = this.getGeo();
var currentPosition = new google.maps.LatLng(geo.getLatitude(), geo.getLongitude());
this.createMarker(currentPosition);
//request set for Places Services
var request = {
location: currentPosition,
radius: 500,
types: ['store']
};
this.getMap().zoom = 15;
// Call PlacesService
var service = new google.maps.places.PlacesService(this.getMap());
service.nearbySearch(request, this.callbackPlaces);
},
callbackPlaces: function(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
addMarker(results[i]);
}
}
},
createMarker: function(position) {
//Here Position = Google Map LatLng
var infoWindow = new google.maps.InfoWindow();
var marker = new google.maps.Marker({
map: this.getMap(),
position: position
});
google.maps.event.addListener(marker, "click", function() {
infoWindow.setContent("Lng: " + marker.position.lng() + "\n Lat: " + marker.position.lat());
infoWindow.open(this.getMap(), marker);
});
},
addMarker: function() {
//Here Place = google.maps.places
var infoWindow = new google.maps.InfoWindow();
var marker = new google.maps.Marker({
map: this.getMap(),
position: place.geometry.location
});
google.maps.event.addListener(marker, "click", function() {
infoWindow.setContent("Lng: " + marker.position.lng() + "\n Lat: " + marker.position.lat());
infoWindow.open(this.getMap(), marker);
});
}
});
I don't know what went wrong!
Any help|hint would appreciated!
Thanks in advance.
You pointed out there was a scope issue in the callbackPlaces function.
Therefore you should replace the following line:
service.nearbySearch(request, this.callbackPlaces);
with
service.nearbySearch(request, function (results, status) {
this.callbackPlaces.call(this, [results, status]);
});
Hope this helps
I am working in a project to provide a map to mobile phone. For now I am trying on a iPhone.
It works fine, and when I load my first page I can see a map with my position, and the market is refreshed each 10 sec and move to my next position.
Some time when I change of page and I come back to the first page, the map is not full displayed. If I move the map, it move but some image of the map is still not displayed.
Also I am working with jquery mobe.
I also noticed that each time I return to the first map, the map is reloaded.
Is there a way to load the map once?
So how can i check that my map is already loaded?
Here is my code
$('#home').live('pagebeforeshow', function(e){
// Resize #mapHome (#mapHome = Sreen hight - footer - header)
$('#mapHome').css('height', Resize.content()-2 +'px');
// extract les id des modules existants
navigator.geolocation.getCurrentPosition(function(position){
showMap('mapHome',position.coords.latitude, position.coords.longitude);
//console.log(position.coords.latitude, position.coords.longitude);
},
function(){
//error
},
{
enableHighAccuracy : true,
maximumAge : 30000
//maximumAge:Infinity
});
// Place and move the marker regarding to my position and deplacement
var track_id = "me";
Tracking.watch_id = navigator.geolocation.watchPosition(
// Success
function(position){
console.log('WatchPosition called');
var lat = position.coords.latitude;
var long = position.coords.longitude;
var latLng = new Array();
latLng[0] = lat;
latLng[1] = long;
//Tracking.myCoordinates.push(lat,long);
Tracking.myCoordinates.push(latLng);
addMarker(lat, long);
},
// Error
showError,
{
frequency: 1000
});
})
I just changed that line to
$('#home').live('pageshow', function(e){... code...}
And it semas to be better but I am not sure-
Here is the code of my function showMap()
function showMap(canvas,lat,long){
var latLng = new google.maps.LatLng(lat,long);
// Google Map options var myOptions = {
zoom: 19,
//zoomControl : 1,
center: latLng,
mapTypeId: google.maps.MapTypeId.ROADMAP////ROADMAP, SATELLITE, HYBRID and TERRAIN };
// Create the Google Map, set options Tracking.mapy = new google.maps.Map(document.getElementById(canvas), myOptions);
}
And here is the code addMarker()
function addMarker(lat, long){
Tracking.mapBounds = new google.maps.LatLngBounds();
// Clean previous markers
for (var i = 0; i < Tracking.markers.length; i++ ) {
Tracking.markers[i].setMap(null);
}
// Add the owner's marker
var latitudeAndLongitude = new google.maps.LatLng(lat, long);
var image = "img/iconGoogleMap/phones.png";
marker = new google.maps.Marker({
title : 'me',
//animation: google.maps.Animation.DROP, //BOUNCE
position: latitudeAndLongitude,
map : Tracking.mapy,
icon : image
});
Tracking.markers.push(marker);
//Tracking.markers.push(marker);
//console.log(localStorage.getItem('mapToDisplay'));
/* ADDING MODULES MAKERS */
// Store the ID of available module.
modulesJSON = Modules.get('bipme');
for (var i = 0; i < modulesJSON['modules'].length; i++) {
console.log('module id = ' +modulesJSON['modules'][i].id);
console.log('Module ' + modulesJSON['modules'][i].id + ' position : ' + ModulesPos.module(modulesJSON['modules'][i].id));
nlatLong = ModulesPos.module(modulesJSON['modules'][i].id).split(",");
var LatitudeAndLongitudeModules = new google.maps.LatLng(nlatLong[0],nlatLong[1]);
var image = "img/iconGoogleMap/" + modulesJSON['modules'][i].profile + "-" + modulesJSON['modules'][i].iconColor + ".png";
marker = new google.maps.Marker({
title : modulesJSON['modules'][i].pseudo,
//animation: google.maps.Animation.DROP, //BOUNCE
position: LatitudeAndLongitudeModules,
map : Tracking.mapy,
icon : image
});
Tracking.mapBounds.extend(LatitudeAndLongitudeModules);
Tracking.markers.push(marker);
};
By the way, is there a way to create a button, from which I can manually refresh the map?
I want to pass related marker id by clicking marker on google map. I am using marker.getId() function to retrieve marker id. But the marker id is not passing along with url. How can i do this? Any Help?
function AddressMap(lat,lang,markerid)
{
var latLng = new google.maps.LatLng(lat,lang);
var marker = new google.maps.Marker({
'map': map,
position: latLng,
'latitude' :lat,
'longitude' :lang,
icon: image,
shadow: shadow,
id: markerid
});
markers.push(marker);
google.maps.event.addListener(marker, 'click', function() {
window.location = "www.cickstart.com/" + marker.getId();
});
}
you can try directly to access the id:
google.maps.event.addListener(marker, 'click', function() {
window.location = "www.cickstart.com/" + marker.id;
});
the best way to do this is add a metadata to marker
var marker = new google.maps.Marker(markerOptions);
marker.metadata = {type: "point", id: 1};
if you have so many marker push the marker to array marker.
You can add any data that you want. and simply call it, set it or get it.
the sample like this one:
markers[0].metadata.id