laravel google map current position - javascript

My javascript Code here is giving me lat and lang if only I moved the curser I need when I get location
lat and lang will get updated to and if I didn't move the cursor or choose location default not working
Here I get current location
const getCurrentPosition = function () {
if (!navigator.geolocation) {
return;
}
const geoLocation = navigator.geolocation;
const currentPositionPromise = new Promise((resolve, reject) => {
geoLocation.getCurrentPosition(
position => {
resolve(position.coords);
},
error => reject(error)
);
});
return currentPositionPromise;
};
getCurrentPosition()
.then(pos => console.log(pos.latitude, pos.longitude))
.catch(err => console.log(err));
This is My Main Function first I get current location
function initialize() {
getCurrentPosition()
.then(pos => {
var e = new google.maps.LatLng(pos.latitude, pos.longitude),
t = {
zoom: 5,
center: e,
panControl: !0,
scrollwheel: 1,
scaleControl: !0,
overviewMapControl: !0,
overviewMapControlOptions: {
opened: !0
},
mapTypeId: google.maps.MapTypeId.terrain
};
map = new google.maps.Map(document.getElementById("latlongmap"), t), geocoder = new google.maps.Geocoder, marker = new google.maps.Marker({
position: e,
map: map
}), map.streetViewControl = !1, infowindow = new google.maps.InfoWindow({
content: "("+pos.latitude+","+ pos.longitude+"))"
}), google.maps.event.addListener(map, "click", function (e) {
marker.setPosition(e.latLng);
var t = e.latLng,
o = "(" + t.lat().toFixed(6) + ", " + t.lng().toFixed(6) + ")";
infowindow.setContent(o),
document.getElementById("lat").value = t.lat().toFixed(6),
document.getElementById("lng").value = t.lng().toFixed(6)
})
})
.catch(err => {
var e = new google.maps.LatLng(24.701925,46.675415),
t = {
zoom: 5,
center: e,
panControl: !0,
scrollwheel: 1,
scaleControl: !0,
overviewMapControl: !0,
overviewMapControlOptions: {
opened: !0
},
mapTypeId: google.maps.MapTypeId.terrain
};
I think the problem is here in this code below
map = new google.maps.Map(document.getElementById("latlongmap"), t), geocoder = new google.maps.Geocoder, marker = new google.maps.Marker({
position: e,
map: map
}), map.streetViewControl = !1, infowindow = new google.maps.InfoWindow({
content: "(24.701925,46.675415))"
}), google.maps.event.addListener(map, "click", function (e) {
marker.setPosition(e.latLng);
var t = e.latLng,
o = "(" + t.lat().toFixed(6) + ", " + t.lng().toFixed(6) + ")";
infowindow.setContent(o),
document.getElementById("lat").value = t.lat().toFixed(6),
document.getElementById("lng").value = t.lng().toFixed(6)
})
});
}

Related

Google maps intermittently loads without styles

I have a google map that loads without styles maybe 1 out of 30 refreshes and I think it's the way / order in which I'm loading the map json and the map data. I'm not quite sure the best way to do this so the styles are always there. I don't think this requires any async functions but not sure.
import MarkerClusterer from '#google/markerclusterer';
const currentPage = $('body').attr('id');
const hasMap = currentPage === 'homePage' || currentPage === 'venuesPage';
let infoArr = [];
let infowindow;
let latLng;
let mapStyles;
let marker;
let markerAddress;
let markerCluster;
let markerCount = -1;
let markerIcon;
let markerInfo;
let markers = [];
let zoomFactor = 4;
$.get('../../data/mapStyles.json').done(data => {
mapStyles = data;
});
$.get('/data/venues.json').done((data) => {
if (hasMap) { // does this need to be hasMap && mapStyles?
initializeMap(data);
}
});
let mcOptions = {
gridSize: 40,
maxZoom: 16,
zoomOnClick: true,
minimumClusterSize: 2,
styles: [
{
height: 53,
url: '/img/meta/m1.png',
width: 53,
},
{
height: 56,
url: '/img/meta/m2.png',
width: 56,
},
{
height: 66,
url: '/img/meta/m3.png',
width: 66,
},
{
height: 78,
url: '/img/meta/m4.png',
width: 78,
},
{
height: 90,
url: '/img/meta/m5.png',
width: 90,
},
],
};
function initializeMap(data) {
if ($(window).width() < 768) {
zoomFactor = 3;
}
let map = new google.maps.Map(document.getElementById('mapContainer'), {
zoom: zoomFactor,
center: new google.maps.LatLng(40.0, -102.0),
styles: mapStyles,
zoomControl: true,
mapTypeControl: false,
scaleControl: false,
streetViewControl: false,
rotateControl: false,
fullscreenControl: false,
mapTypeId: google.maps.MapTypeId.ROADMAP,
});
markerIcon = '/img/svgs/icon_map_marker_venue.svg';
data.forEach((venue) => {
let {
lat,
long,
name,
streetAddress,
city,
state,
slug,
} = venue;
if (lat !== '') {
latLng = new google.maps.LatLng(lat, long);
marker = new google.maps.Marker({
position: latLng,
icon: markerIcon,
});
markerAddress = `${streetAddress}<br>${city}, ${state}`;
markerInfo = `<a class="map-marker" href="/venues/venue-detail/index.php?${slug}"><h5>${name}</h5>${markerAddress}</a>`;
markers.push(marker);
infoArr.push(markerInfo);
markerCount += 1;
}
google.maps.InfoWindow.prototype.isOpen = function () {
let map = this.getMap();
return (map !== null && typeof map !== 'undefined');
};
infowindow = new google.maps.InfoWindow({});
google.maps.event.addListener(marker, 'click', (function (marker, markerCount) {
return function () {
if (!infowindow.isOpen()) {
infowindow.setContent(infoArr[markerCount]);
infowindow.open(map, marker);
} else {
infowindow.close();
}
};
}(marker, markerCount)));
});
markerCluster = new MarkerClusterer(map, markers, mcOptions);
}
I did the the json gets like this and it works:
$.when($.get('../../data/mapStyles.json').done(styleData => {
mapStyles = styleData;
}), $.get('/data/venues.json').done(vData => {
venueData = vData;
})).then(() => {
initialize(venueData);
});

to realize clustering on the GoogleMap

How to realize clustering of markers on the map? Help me clear errors. necessary scripts are connected. Error: enter image description here
function CustomMarker(latlng, map, imageSrc) {
this.latlng_ = latlng;
this.imageSrc = imageSrc;
this.setMap(map);
}
CustomMarker.prototype = new google.maps.OverlayView();
...
var map = new google.maps.Map(document.getElementById("map"), {
zoom: 17,
center: new google.maps.LatLng(48.42216, 44.31308),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var data = [{
profileImage: "./images/1.jpg",
pos: [48.42217, 44.31308]
}, {
profileImage: "./images/2.jpg",
pos: [48.42220, 44.31308]
}];
for(var i=0;i<data.length;i++){
new CustomMarker(new google.maps.LatLng(data[i].pos[0],data[i].pos[1]), map, data[i].profileImage)
}
var markerCluster = new MarkerClusterer(map, data,
{imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m'});
Please find this code snippet might help your cause.
function initialize(markers) {
map = new google.maps.Map(document.getElementById('main-map'), {
zoom:3,
center: new google.maps.LatLng(markers[0].Latitude, markers[0].Longitude),
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: false,
streetViewControl: false,
panControl: false,
zoomControlOptions: {
position: google.maps.ControlPosition.LEFT_BOTTOM
}
});
for (var i = 0; i < markers.length; i++) {
var image = '/Festool/media/Festool%20Images/Festool%20Icons/location-icon.png';
var marker = new google.maps.Marker({
position: new google.maps.LatLng(markers[i].Latitude, markers[i].Longitude),
map: map,
icon:image,
title: 'Click to zoom'
});
var infowindow = new google.maps.InfoWindow({
maxWidth: 250,
});
mar.push(marker);
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent( ContentString(i));
infowindow.open(map, marker);
}
})(marker, i));
}
}

Reutilize maps markers for weighted heatMaps

I'm using this functions to get markers via Ajax, and draw it in a map_canvas div. That works perfectly, and I'm trying to reuse the "gmarkers" variable to create a heatmap...with no luck. How can I create a heatmap with this data?
I prefer to use the same data I'm loading with this function weighting the heatmap by variable: llamados.
How can I start?
var gmarkers = [];
function initialize() {
var myOptions = {
zoom: 10,
center: mapCenter,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map_canvas'), myOptions);
current_zoom = map.getZoom();
var myControl = document.getElementById('descripcion');
map.controls[google.maps.ControlPosition.RIGHT_BOTTOM].push(myControl);
}
google.maps.event.addDomListener(window, 'load', initialize);
var infowindow = new google.maps.InfoWindow();
var bounds = new google.maps.LatLngBounds();
var marker, i;
var myLatLng;
function CreateMarker (obj, i) {
myLatLng = new google.maps.LatLng(obj['lat'], obj['lon']);
marker = new google.maps.Marker({
position: myLatLng,
animation: google.maps.Animation.DROP,
title: obj['nodo'],
llamados: obj['llamados'],
icon: obj['icono'],
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent('Nodo: ' + obj['nodo'] + '; Llamados: ' + obj['llamados']);
infowindow.open(map, marker);
}
})(marker, i));
gmarkers.push(marker);
}
function ejecutarAjax(){
$.ajax({
beforeSend: function() {
},
cache: false,
// data: params,
dataType: 'json',
timeout: 0,
type: 'POST',
url: 'traerLlamados.php',
success: function(data) {
if (data) {
var data = data;
var obj;
cantidad=Object.keys(data).length;
for(var i in data){
CreateMarker(data[i]);
};
}
else {
alert('No data');
}
},
});
}
Given your existing code, you should be able to add a heatmap to the map (after the markers are loaded) by doing:
var heatmapArray = [];
for (var i=0; i<gmarkers.length; i++) {
heatmapArray.push({location: gmarkers[i].getPosition(), weight: gmarkers[i].llamados});
}
var heatmap = new google.maps.visualization.HeatmapLayer({
data: heatmapArray
});
heatmap.setMap(map);
Proof of concept fiddle
Code snippet:
var gmarkers = [];
var mapCenter = new google.maps.LatLng(37.782, -122.447);
function initialize() {
var myOptions = {
zoom: 15,
center: mapCenter,
mapTypeId: google.maps.MapTypeId.SATELLITE
};
map = new google.maps.Map(document.getElementById('map_canvas'), myOptions);
current_zoom = map.getZoom();
var myControl = document.getElementById('descripcion');
map.controls[google.maps.ControlPosition.RIGHT_BOTTOM].push(myControl);
for (var i = 0; i < heatMapData.length; i++) {
// Translate into obj expected by CreateMarker
var obj = {
lat: heatMapData[i].location.lat(),
lon: heatMapData[i].location.lng(),
nodo: "nodo" + i,
llamados: heatMapData[i].weight,
icono: "http://maps.google.com/mapfiles/ms/micons/blue.png"
}
CreateMarker(obj, i);
}
var heatmapArray = [];
for (var i = 0; i < gmarkers.length; i++) {
heatmapArray.push({
location: gmarkers[i].getPosition(),
weight: gmarkers[i].llamados
});
}
var heatmap = new google.maps.visualization.HeatmapLayer({
data: heatmapArray
});
heatmap.setMap(map);
}
google.maps.event.addDomListener(window, 'load', initialize);
var infowindow = new google.maps.InfoWindow();
var bounds = new google.maps.LatLngBounds();
var marker, i;
var myLatLng;
function CreateMarker(obj, i) {
myLatLng = new google.maps.LatLng(obj['lat'], obj['lon']);
marker = new google.maps.Marker({
position: myLatLng,
animation: google.maps.Animation.DROP,
title: obj['nodo'],
llamados: obj['llamados'],
icon: obj['icono'],
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent('Nodo: ' + obj['nodo'] + '; Llamados: ' + obj['llamados']);
infowindow.open(map, marker);
}
})(marker, i));
gmarkers.push(marker);
}
google.maps.event.addDomListener(window, "load", initialize);
/* Data points defined as a mixture of WeightedLocation and LatLng objects */
var heatMapData = [{
location: new google.maps.LatLng(37.782, -122.447),
weight: 0.5
}, {
location: new google.maps.LatLng(37.782, -122.445),
weight: 1
}, {
location: new google.maps.LatLng(37.782, -122.443),
weight: 2
}, {
location: new google.maps.LatLng(37.782, -122.441),
weight: 3
}, {
location: new google.maps.LatLng(37.782, -122.439),
weight: 2
}, {
location: new google.maps.LatLng(37.782, -122.437),
weight: 10
}, {
location: new google.maps.LatLng(37.782, -122.435),
weight: 0.5
}, {
location: new google.maps.LatLng(37.785, -122.447),
weight: 3
}, {
location: new google.maps.LatLng(37.785, -122.445),
weight: 2
}, {
location: new google.maps.LatLng(37.785, -122.443),
weight: 5
}, {
location: new google.maps.LatLng(37.785, -122.441),
weight: 0.5
}, {
location: new google.maps.LatLng(37.785, -122.439),
weight: 1
}, {
location: new google.maps.LatLng(37.785, -122.437),
weight: 2
}, {
location: new google.maps.LatLng(37.785, -122.435),
weight: 3
}];
html,
body,
#map_canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?libraries=geometry,visualization"></script>
<div id="map_canvas"></div>

Google Maps API V3: Exclude single marker from clustering

I am using the google maps api and using grid clustering for the markers. I wanted to know if there is a way to exclude a single marker from clustering. I want a "You are here" marker that is always visible. I tried using a different array for just that marker and not including it the cluster function but that didn't work.
Does anyone have a solution for this?
Here is how i am doing the clustering
$(document).on('click', '#mapbut', function() {
var items, distances, you_are_here = [], markers_data = [], markers_data2 = [], fred, clust1, markss;
you_are_here.push({
lat : Geo.lat,
lng : Geo .lng,
animation: google.maps.Animation.DROP,
title : 'Your are here',
icon: {
path: google.maps.SymbolPath.CIRCLE,
scale: 10
},
infoWindow: {
content: '<p>You are Here</p>'
}
});
function loadResults (data) {
if (data.map.length > 0) {
items = data.map;
for (var i = 0; i < items.length; i++)
{
var item = items[i];
var distances = [];
var dist2;
if (item.Lat != undefined && item.Lng != undefined)
{
markers_data.push({
lat : item.Lat,
lng : item.Lng,
title : item.Site,
infoWindow: {
content: '<p>' + item.Site + '</p><p>' + Math.round(item.distance) + ' miles away</p>'
}
});
}
}
}
map.addMarkers(markers_data);
map = new GMaps({
el: '#map',
lat: Geo.lat,
lng: Geo.lng,
zoom: 10,
mapTypeControl: false,
zoomControl: true,
zoomControlOptions: {
position: google.maps.ControlPosition.LEFT_CENTER
},
markerClusterer: function(map) {
options = {
gridSize: 50
}
clust1 = new MarkerClusterer(map,[], options);
return clust1;
},
scaleControl: true,
streetViewControl: false
});
map.addMarkers(you_are_here);
The GMaps clusters all the markers you add to it with the addMarker method (if you provide a MarkerClusterer).
One option: add your "special" marker (the one that you don't want clustered) to the map manually, so it isn't added to the MarkerClusterer:
The GMaps.map property is a reference to the Google Maps Javascript API v3 map object. So this will add a marker to the map without letting the GMaps library know about it:
you_are_here = new google.maps.Marker({
position: {lat: Geo.lat,lng: Geo.lng},
animation: google.maps.Animation.DROP,
title: 'Your are here',
icon: {
path: google.maps.SymbolPath.CIRCLE,
scale: 10
},
map: map.map
});
proof of concept fiddle
code snippet:
var Geo = {
lat: 40.7281575,
lng: -74.07764
};
$(document).on('click', '#mapbut', function() {
var items, distances, you_are_here = [],
markers_data = [],
markers_data2 = [],
fred, clust1, markss;
function loadResults(data) {
if (data.map.length > 0) {
items = data.map;
for (var i = 0; i < items.length; i++) {
var item = items[i];
var distances = [];
var dist2;
if (item.Lat != undefined && item.Lng != undefined) {
markers_data.push({
lat: item.Lat,
lng: item.Lng,
title: item.Site,
infoWindow: {
content: '<p>' + item.Site + '</p><p>' + Math.round(item.distance) + ' miles away</p>'
}
});
}
}
}
map = new GMaps({
el: '#map',
lat: Geo.lat,
lng: Geo.lng,
zoom: 8,
mapTypeControl: false,
zoomControl: true,
zoomControlOptions: {
position: google.maps.ControlPosition.LEFT_CENTER
},
markerClusterer: function(map) {
options = {
gridSize: 50,
imagePath: "https://cdn.rawgit.com/googlemaps/v3-utility-library/master/markerclustererplus/images/m"
}
clust1 = new MarkerClusterer(map, [], options);
return clust1;
},
scaleControl: true,
streetViewControl: false
});
map.addMarkers(markers_data);
you_are_here = new google.maps.Marker({
position: {
lat: Geo.lat,
lng: Geo.lng
},
animation: google.maps.Animation.DROP,
title: 'Your are here',
icon: {
path: google.maps.SymbolPath.CIRCLE,
scale: 10
},
infoWindow: {
content: '<p>You are Here</p>'
},
map: map.map
});
// map.addMarkers(you_are_here);
}
loadResults(data);
});
var data = {
map: [{
Lat: 40.7127837,
Lng: -74.005941,
Site: "New York, NY",
distance: 1
}, {
Site: "Newark, NJ",
Lat: 40.735657,
Lng: -74.1723667,
distance: 2
}]
};
html,
body,
#map {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js"></script>
<script src="https://rawgit.com/HPNeo/gmaps/master/gmaps.js"></script>
<script src="https://cdn.rawgit.com/googlemaps/v3-utility-library/master/markerclustererplus/src/markerclusterer.js"></script>
<input id="mapbut" type="button" value="map" />
<div id="map"></div>
To get around this is relatively simple, just after I send the markers array to MarkerClusterer I then add my location.
// Setup cluster markers
var markerCluster = new MarkerClusterer( gmap.map, options )
// add my location
gmap.addMarker({
lat: data.latitude,
lng: data.longitude
...
})
Thanks

First create marker on google maps take too much time

I'm using the google maps API V3 in javascript and Vue.js for my application and i have found a strange bug, when i click the first time to put a marker on the map, the web app froze during 1-3seconds. Here is my code:
var vueMap = new Vue({
el: '#map-canvas',
data: {
infowindow: new google.maps.InfoWindow(
{
size: new google.maps.Size(150,50)
}),
marker: null
},
ready:function(){
this.initialize();
},
methods: {
createMarker: function (latlng, name, html, point1, map) {
var distanceKm = google.maps.geometry.spherical.computeDistanceBetween(point1, latlng);
distanceKm = distanceKm/1000;
distanceKm = distanceKm.toFixed(2);
var contentString = "Distance en KM ---- " + distanceKm + '<br/>Score de 123';
// HERE IS WHERE THE FROZE HAPPEN
this.marker = new google.maps.Marker({
position: latlng,
map: map,
zIndex: Math.round(latlng.lat()*-100000)<<5
});
// TODO onclick
google.maps.event.addListener(this.marker, 'click', function() {
this.infowindow.setContent(contentString);
this.infowindow.open(map,this.marker);
}.bind(this));
google.maps.event.trigger(this.marker, 'click');
return this.marker;
},
initialize: function () {
var styles = [/*some style*/];
var styledMap = new google.maps.StyledMapType(styles,
{name: "Styled Map"});
var bounds = new google.maps.LatLngBounds(
new google.maps.LatLng(48.815145,2.244830),
new google.maps.LatLng(48.902137, 2.417864)
);
var point1 = new google.maps.LatLng(48.858230, 2.372566);
var center = bounds.getCenter();
var x = bounds.contains(center);
var mapOptions = {
mapTypeControlOptions: {
mapTypeIds: [google.maps.MapTypeId.ROADMAP, 'map_style']
},
center: center,
zoom: 1,
minZoom: 13,
streetViewControl: false,
mapTypeControl: false,
zoomControl: true,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.LARGE,
position: google.maps.ControlPosition.RIGHT_CENTER
},
panControl: true,
panControlOptions: {
position: google.maps.ControlPosition.RIGHT_CENTER
}
};
console.log(document.getElementById('map-canvas'));
var map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
var lastValidCenter = map.getCenter();
map.mapTypes.set('map_style', styledMap);
map.setMapTypeId('map_style');
google.maps.event.addListener(map, 'center_changed', function() {
if (bounds.contains(map.getCenter())) {
// still within valid bounds, so save the last valid position
lastValidCenter = map.getCenter();
return;
}
// not valid anymore => return to last valid position
map.panTo(lastValidCenter);
});
google.maps.event.addListener(map, 'click', function(event) {
//call function to create marker
if (this.marker != null) {
this.marker.setMap(null);
this.marker = null;
}
this.marker = vueMap.createMarker(event.latLng, "name", "<b>Location</b><br>"+event.latLng, point1, map);
}.bind(this));
}
}
});
module.exports = vueMap;
It's longer on Chrome than with Firefox and Safari...
Does someone knows why ? (Or have a clue about it ?)
Thanks in advance

Categories

Resources