How To Make a Map Center on User's Location - javascript

How do I make a map center on the client's current location, but default to the LatLng below if the current location can't be determined.
var myOptions = {
center: new google.maps.LatLng(12.659493, 79.415412),
zoom: 12,
scrollwheel: false,
mapTypeId: google.maps.MapTypeId.ROADMAP
}

You can use the HTML 5 Geolocation functions for this purpose. It's close but not super precise.
Demo
var map;
function initialize() {
if(navigator.geolocation) {
success = function(position) {
createMap(position.coords.latitude, position.coords.longitude);
};
error = function() { createMap(12.659493, 79.415412); }
navigator.geolocation.getCurrentPosition(success, error);
}
else {
createMap(12.659493, 79.415412);
}
}
function createMap(lat, lng) {
var mapOptions = { center: new google.maps.LatLng(lat, lng),
zoom: 12,
scrollwheel: false,
mapTypeId: google.maps.MapTypeId.ROADMAP };
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
}

Related

Google Map Marker Clustering not Working on zoom out

I am trying to work with Google map marker clustering in Javascript. And i am pretty new to this.
The scenario
I am fetching a huge chunk of data from database in the lot of 10000 per call and then rendering the set on google map by sending the lat lng array to the marker cluster.
My data set consists of 100000 outlets. I am fetching 10000 outlets at once and this is being called 10 times so 10 clusters of 10000 are getting created and they are overlapping with each other. When i try to zoom in the cluster expands into further small clusters.
But while zooming out instead of the clustering back they overlap.
Issue- Need to get all the 100000 outlets in one cluster on zoom out .
or if that is not possible then how to fix the overlapping?
This is the code snippet
var mapDiv = document.getElementById('newmap');
map = new google.maps.Map(mapDiv, {
center: new google.maps.LatLng(latitude, longitude),
zoom: 3,
panControl: true,
mapTypeControl: true,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
},
zoomControl: true,
zoomControlOptions: {
position: google.maps.ControlPosition.LEFT_TOP,
},
streetViewControl: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
function addMarker1(locations, outletname, outletData) {
var infoWindow = new google.maps.InfoWindow();
var markers = locations.map(function(location, i) {
return new google.maps.Marker({
position: location,
});
});
var markerCluster = new MarkerClusterer(map, markers, {
imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m'
});
}
// this is sending data 10000 each
for (var i = 0; i < outletDataLen; i++) {
outletArray.push(outletData[i]['Outletview']['name']);
j.push({
lat: parseFloat(outletData[i]['Outletview']['latitude']),
lng: parseFloat(outletData[i]['Outletview']['longitude'])
});
outletname.push(outletData[i]['Outletview']['name']);
}
addMarker1(j, outletname, outletData);
Take the markers from the MarkerCluster object and concat new Markers data with it and add it to the same Markerobject as below and also refer the API
var mapDiv = document.getElementById('newmap');
map = new google.maps.Map(mapDiv, {
center: new google.maps.LatLng(latitude, longitude),
zoom: 3,
panControl: true,
mapTypeControl: true,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
},
zoomControl: true,
zoomControlOptions: {
position: google.maps.ControlPosition.LEFT_TOP,
},
streetViewControl: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var markerCluster = new MarkerClusterer(map, [], {
imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m'
});
function addMarker1(locations, outletname, outletData) {
var infoWindow = new google.maps.InfoWindow();
var markers = locations.map(function(location, i) {
return new google.maps.Marker({
position: location,
});
});
var mapmarkers = markerCluster.getTotalMarkers();
markers = markers.concat(mapmarkers);
markerCluster.addMarkers(markers);
markerCluster.redraw();
}
// this is sending data 10000 each
for (var i = 0; i < outletDataLen; i++) {
outletArray.push(outletData[i]['Outletview']['name']);
j.push({
lat: parseFloat(outletData[i]['Outletview']['latitude']),
lng: parseFloat(outletData[i]['Outletview']['longitude'])
});
outletname.push(outletData[i]['Outletview']['name']);
}
addMarker1(j, outletname, outletData);
The solution is to clear the data before looping through the markers
if (markerCluster)
{
markerCluster.clearMarkers();
markerCluster.resetViewport();
markers = [];
markerCluster.removeMarker(new_arr);
}

ReferenceError: Method is not defined (Mockup js)

I would like to fetchDriver() every few minutes, but I am unable to call fetchDriver() out side the initMap().
fetchDriver() calls on my api and drops a marker on the map to provide the "drivers" location.
I need to call fetchDriver from outside the initmap so the map remains static for the mos part.
Thanks for any help on this issue.
<div id="map" style="width: 100%; height: 400px" class="img-thumbnail"></div>
<script>
var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 0000, lng: 0000},
zoom: 10,
minZoom: 10,
maxZoom: 15,
scrollwheel: false,
streetViewControl: false,
mapTypeControl: false
});
function fetchDriver() {
$.get('api call', function (responseText) {
var obj = JSON.parse(responseText);
var location = {lat: parseFloat(obj.latitude), lng: parseFloat(obj.longitude)};
addMarker(location);
});
}
function addMarker(location) {
var marker = new google.maps.Marker({
position: location,
map: map
});
}
}
</script>
<script>
fetchDriver();
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=MyKeycallback=initMap" async defer></script>

Google map (mapTypeControlOptions) is not working

I would like to position my satellite button to the center of the map but however is not working. Would appreciate if anyone can assist here. thanks.
function initialize() {
$(q).addClass('fmp_responsive_map');
startMap(true);
var mapProp = {
mapTypeControl: true,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR,
position: google.maps.ControlPosition.TOP_CENTER
},
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map-canvas"),mapProp);
$('input[type="submit"], button[type="submit"]', $(y.searchForm))
.on('click', function(a) {
a.preventDefault();
var b = $(y.searchForm).attr("action");
searchData(b)
})
}
Tried the working sample found here, and made changes to the following code.
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 12,
center: {lat: -28.643387, lng: 153.612224},
mapTypeControl: true,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR,
position: google.maps.ControlPosition.CENTER
},
...
That's it. Try using CENTER.

How to make Google Maps V3 polyline snap to road from given points?

I try to make a polyline snap to road from given marker points. My problem is, that the same
code sometimes gives the good results, like in this image
and sometimes a bad result, like this:
Any ideas why this is hapenning? And also, is there a limitation for polyline snap to road?
My map ini code:
var myLatlng = new google.maps.LatLng(47.6557, 23.5833);
var mapOptions = {
zoom: 14,
minZoom: 13,
maxZoom: 19,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
disableDefaultUI: true,
overviewMapControl: false,
streetViewControl: false,
scaleControl: false,
mapTypeControl: false,
panControl: true,
panControlOptions:{
position: google.maps.ControlPosition.TOP_RIGHT
},
zoomControl: true,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.LARGE,
position: google.maps.ControlPosition.TOP_RIGHT
}
}
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
My polyline route snap code:
var polys = new google.maps.Polyline({
map: map,
strokeColor: "#5555FF"
});
myCoord = [
new google.maps.LatLng(47.663383463156144, 23.58100461977301),
new google.maps.LatLng(47.659221287827435, 23.586240291770082),
new google.maps.LatLng(47.65534785438211, 23.576713085349184),
new google.maps.LatLng(47.66020405359421, 23.572249889548402)
];
// BEGIN: Snap to road
var service = new google.maps.DirectionsService(),polys,snap_path=[];
polys.setMap(map);
placeMarker(myCoord[0], map);
for(j=0;j<myCoord.length-1;j++){
service.route({origin: myCoord[j],destination: myCoord[j+1],travelMode: google.maps.DirectionsTravelMode.DRIVING},function(result, status) {
if(status == google.maps.DirectionsStatus.OK) {
snap_path = snap_path.concat(result.routes[0].overview_path);
polys.setPath(snap_path);
}
});
}
If you just want directions with waypoints, you should just call the directionsService once with those waypoints, something like this (not tested):
var service = new google.maps.DirectionsService();
var directionsDisplay = new google.maps.DirectionsRenderer();
directionsDisplay.setMap(map);
var waypts = [];
for(j=1;j<myCoord.length-1;j++){
waypts.push({location: myCoord[j],
stopover: true});
}
var request = {
origin: myCoord[0],
destination: myCoord[myCoord.length-1],
waypoints: waypts,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
service.route(request,function(result, status) {
if(status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(result);
} else { alert("Directions request failed:" +status); }
});
Note: there is a maximum of 8 waypoints with the free API.

How to use MarkerClusterer in the google maps api

How can I use MarkerClusterer in the Google Maps API? I tried to use it, but it's not working.
My code is written as follow.
function InitializeMap(lat, lng, location, username, town, is_paid) {
var myOptions;
var latlng = new google.maps.LatLng(lat, lng);
if (is_paid != "True") {
myOptions = {
zoom: 10,
center: latlng,
scrollwheel: false,
streetViewControl: false,
//navigationControlOptions: {style: google.maps.NavigationControlStyle.SMALL},
//scaleControl: false,
navigationControl: false,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
}
else {
myOptions = {
zoom: 10,
center: latlng,
scrollwheel: true,
streetViewControl: true,
navigationControlOptions: { style: google.maps.NavigationControlStyle.SMALL },
mapTypeId: google.maps.MapTypeId.ROADMAP
};
}
map = new google.maps.Map(document.getElementById('map'), myOptions);
var mcOptions = {gridSize: 100, maxZoom: 10};
generateMarkers(location, is_paid);
generateUserMarker(lat, lng, username, town, is_paid);
alert(groupMarkers.length);
var mc = new MarkerClusterer(map, groupMarkers, mcOptions);
//mc.addMarkers(groupMarkers,true);
alert("hello");
}
function generateMarkers(locations, is_paid) {
var marker
for (var i = 0; i < locations.length; i++) {
createMarker(new google.maps.LatLng(locations[i][0], locations[i][1]), locations[i][2], locations[i][3], is_paid);
}
}
function createMarker(pos, name, town, is_paid) {
var infowindow;
var marker = new google.maps.Marker({
position: pos,
map: map, // google.maps.Map
title: name,
icon: "images/red.png"
});
groupMarkers.push(marker);
}

Categories

Resources