How to Check Current Time with Restaurant Times on Google Maps API - javascript

I'm looking for a way to check the current local time with the restaurant's opening and closing time. I'm using Google Maps API and I have been able to show some restaurants on the map. The map centre is Adelaide, Australia, but the tool asks for the user location and goes there. I want to compare the time and if the time is not in between, the restaurant should not be on the map. Also, if the hours are not set for a restaurant, then the tool should display the restaurant all the time.
Here is the CSS and JavaScript code. I have removed the API key.
<div id="map"></div>
<script>
var infoWindow;
var gmarkers = [];
var map;
function initMap() {
infoWindow = new google.maps.InfoWindow();
map = new google.maps.Map(document.getElementById('map'), {
zoom: 13,
center: {lat: -34.9285,lng: 138.6007}
});
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
initialLocation = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
map.setCenter(initialLocation);
});
}
var markers = [
// A
{coords:{lat:-34.92366, lng:138.567063}, content:'<p><strong>Abyssinian Restaurant</strong></p>', timing: {open: 1200, close: 1400}},
// B
{coords:{lat:-34.923885, lng:138.562042}, content:'<p><strong>British Raj</strong></p>', timing: {open: 0800, close: 1700}},
{coords:{lat:-34.843645, lng:138.507653}, content:'<p><strong>Banyan Hotel Port Adelaide</strong></p>', timing: {open: 0900, close: 1900}},
];
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < markers.length; i++) {
gmarkers.push(addMarker(markers[i]));
bounds.extend(markers[i].coords);
}
// map.fitBounds(bounds);
function addMarker(props) {
var currentDate = new Date();
var marker = new google.maps.Marker({
position: props.coords,
map: map,
icon:'Ellipse 1.png'});
if (props.content){
marker.addListener('click', function(){
infoWindow.setContent(props.content);
infoWindow.open(map,marker);});
}
return marker;
}
}
</script>
<script src="markerclusterer.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?key=API_KEY&callback=initMap" async defer></script>
CSS
<style>
#charset "utf-8";
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 80%;
}
/* Optional: Makes the sample page fill the window. */
html, body {
height: 100%;
margin: 0;
padding: 0;
}
</style>

Try modifying your code as follows:
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < markers.length; i++) {
const marker = addMarker(markers[i]);
if (marker) {
gmarkers.push(marker);
bounds.extend(markers[i].coords);
}
}
// map.fitBounds(bounds);
function addMarker(props) {
var currentDate = new Date();
const currentTime = parseInt(currentDate.getHours().toString() + currentDate.getMinutes().toString());
if (props.timing.open > currentTime || props.timing.close < currentTime) {
return false;
}
var marker = new google.maps.Marker({
position: props.coords,
map: map,
icon:'Ellipse 1.png'
});
if (props.content) {
marker.addListener('click', function() {
infoWindow.setContent(props.content);
infoWindow.open(map, marker);
});
}
return marker;
}
My local time is 919 (09:19 AM) so only "Banyan Hotel Port Adelaide" and "British Raj" show up on the map, because "Abyssinian Restaurant" opens at 1200 (12:00 PM).
Hope this helps!

Related

how to refresh maps with ajax request?

I want to reload map in ajax call.This code is reloading whole page when i change status it reloads whole page.I want after 10 seconds only map reloads not whole page. if i select on change available then map reloads after every 10 seconds in available option.
i have drivers if i select status of driver available then map shows the drivers which are available. i want to refresh map after 10 sec so that i can see if there is any other driver available. if available then it will show on map without reloading whole page. This is what i want.
i am refreshing content in some div of the page by using jQuery load() function but its not working.
Html:
<div class="row">
<div class="col-md-12">
<div id="map" style="height: 550px;">
<div id="time">
<?php echo date('H:i:s');?>
</div>
</div>
</div>
</div>
Script:
$('#status').change(function () {
var job_status = $(this).val();
$.ajax({
url: '{{ URL::to('/get_drivers/')}}' + '/' + $(this).val(),
type: 'get',
datatype: 'json',
success: function (response) {
setInterval("my_function();", 10000);
function my_function() {
$('#map').load(location.href + ' #time');
}
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 10,
center: {lat: 31.5204, lng: 74.3587},
mapTypeId: 'roadmap'
});
var infowindow = new google.maps.InfoWindow({});
var marker, i;
{{--var carIcon = '{{asset('images/red-car.png')}}';--}}
if (gmarkers.length > 0) {
for (i = 0; i < gmarkers.length; i++) {
if (gmarkers[i].getMap() != null) {
gmarkers[i].setMap(null);
} else {
gmarkers[i].getMap();
gmarkers[i].setMap(map);
}
}
gmarkers = [];
}
for (i = 0; i < locationData.length; i++) {
if (job_status == 8) {
if (job_status === '') {
gmarkers = [];
}
else {
for (i = 0; i < locationData2.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locationData2[i]['driver_lat'], locationData2[i]['driver_long']),
map: map,
optimized: false,
icon: '{{asset('images/grey-car.png')}}'
});
google.maps.event.addListener(marker, 'mouseover', (function (marker, i) {
return function () {
infowindow.setContent('<h6><b>' + locationData2[i]['first_name'] + '</h6>');
infowindow.open(map, marker);
}
})(marker, i));
google.maps.event.addListener(map, 'click', (function (marker, i) {
return function () {
infowindow.setContent();
infowindow.close(marker);
}
})(marker, i));
// Push your newly created marker into the array:
gmarkers.push(marker);
var myoverlay = new google.maps.OverlayView();
myoverlay.draw = function () {
// add an id to the layer that includes all the markers so you can use it in CSS
this.getPanes().markerLayer.id = 'markerLayer';
};
myoverlay.setMap(map);
}
}
}
});
You do not need to renew the whole map but drivers markers only (or to be even more precise - not whole markers but their positions only)
I use google own example and put there couple of markers which positions get renewed to random location every second.
//random locations
var latArr = [-20.363882, -21.363882, -22.363882, -23.363882, -24.363882, -25.363882, -26.363882, -27.363882, -28.363882, -29.363882];
var lngArr = [125.044922, 126.044922, 127.044922, 128.044922, 129.044922, 130.044922, 131.044922, 132.044922, 133.044922, 134.044922];
//global array to hold all markers
var markersArr = [];
//map init from google example
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: {lat: -25.363882, lng: 131.044922}
});
//create markers
var marker1 = new google.maps.Marker({
position: map.getCenter(),
icon: {
path: google.maps.SymbolPath.CIRCLE,
scale: 10
},
draggable: true,
map: map
});
var marker2 = new google.maps.Marker({
position: map.getCenter(),
icon: {
path: google.maps.SymbolPath.BACKWARD_CLOSED_ARROW,
scale: 5
},
draggable: true,
map: map
});
markersArr.push(marker1);
markersArr.push(marker2);
}
//function to change markers locations
function renewMarkers(){
for(i=0; i<markersArr.length; i++){
var lt = Math.floor(Math.random()*10);
var ln = Math.floor(Math.random()*10);
markersArr[i].setPosition({lat: latArr[lt], lng: lngArr[ln]})
}
}
setInterval(renewMarkers, 1000);
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html, body {
height: 100%;
margin: 0;
padding: 0;
}
<!-- Replace the value of the key parameter with your own API key. -->
<script async defer
src="https://maps.googleapis.com/maps/api/js?callback=initMap">
</script>
<div id="map"></div>

Show nearest elements on google map

I am creating a project using google map. My project contains hospital address ( in longitude and latitude) to be stored in database. But I want to show nearest hospital from my current location. And I am unable to figure out how to do it. Please help me with best algorithm and with some code.
Following code is used just to display all hospital address in map now I want is how to show only 3 nearest hospital from my current positiom.
function initMap() {
var mapType = google.maps.MapTypeId.ROADMAP;
var animationType = google.maps.Animation.DROP;
var currentLocationAnimationType = google.maps.Animation.BOUNCE;
var mapElement = document.getElementById('map');
var nepalLocation = {
lat: 28.3949,
lng: 84.1240
};
var mapOptions = {
center: nepalLocation,
zoom: 7,
mapTypeId: mapType,
};
// actual map
map = new google.maps.Map(mapElement, mapOptions);
var infoWindow = new google.maps.InfoWindow();
var latlngbounds = new google.maps.LatLngBounds();
var geocoder = geocoder = new google.maps.Geocoder();
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(p) {
var LatLng = new google.maps.LatLng(p.coords.latitude, p.coords.longitude);
var marker = new google.maps.Marker({
position: LatLng,
map: map,
title: "My Location",
animation: currentLocationAnimationType
});
google.maps.event.addListener(marker, "click", function(e) {
var infoWindow = new google.maps.InfoWindow();
infoWindow.setContent(marker.title);
infoWindow.open(map, marker);
});
});
} else {
alert('Geo Location feature is not supported in this browser.');
}
for (var i = 0; i < markers.length; i++) {
var data = markers[i]
var myLatlng = new google.maps.LatLng(data.lat, data.lng);
var image = "img/iconHospital.png";
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
icon: image,
title: data.district,
animation: animationType
});
}
}
google.maps.event.addDomListener(window, 'load', initMap);
<!DOCTYPE html>
<html>
<head>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=true&libraries=places"></script>
</head>
<body>
<div id="map"></div>
</body>
</html>
See this example at. I adapted your code accordingly.
function initMap() {
var mapType = google.maps.MapTypeId.ROADMAP;
var animationType = google.maps.Animation.DROP;
var currentLocationAnimationType = google.maps.Animation.BOUNCE;
var mapElement = document.getElementById('map');
var nepalLocation = {
lat: 28.3949,
lng: 84.1240
};
var mapOptions = {
center: nepalLocation,
zoom: 7,
mapTypeId: mapType,
};
// actual map
map = new google.maps.Map(mapElement, mapOptions);
var infoWindow = new google.maps.InfoWindow();
var latlngbounds = new google.maps.LatLngBounds();
var geocoder = geocoder = new google.maps.Geocoder();
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(p) {
var LatLng = new google.maps.LatLng(p.coords.latitude, p.coords.longitude);
var marker = new google.maps.Marker({
position: LatLng,
map: map,
title: "My Location",
animation: currentLocationAnimationType
});
google.maps.event.addListener(marker, "click", function(e) {
var infoWindow = new google.maps.InfoWindow();
infoWindow.setContent(marker.title);
infoWindow.open(map, marker);
});
});
} else {
alert('Geo Location feature is not supported in this browser.');
}
infowindow = new google.maps.InfoWindow();
var service = new google.maps.places.PlacesService(map);
service.nearbySearch({
location: nepalLocation,
radius: 50000,
type: ['hospital']
}, callback);
}
function callback(results, status) {
if (status === google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
if (i == 2) {
break;
}
createMarker(results[i]);
}
}
}
function createMarker(place) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location,
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(place.name);
infowindow.open(map, this);
});
}
google.maps.event.addDomListener(window, 'load', initMap);
<!DOCTYPE html>
<html>
<head>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=true&libraries=places"></script>
<style>
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
</style>
</head>
<body>
<div id="map"></div>
</body>
</html>

Recenter map with multiple markers

I display multiple markers on a map. The list of locations is built with PHP:
$myData .= '["'.$Name.'", '.$lat.', '.$blon.'],';
Then I use JS to plot markers on the map.
function initMap() {
var map = new google.maps.Map(document.getElementById("map"), {
zoom: 12,
center: {lat: 32.99999999, lng: -95.2222328}
});
setMarkers(map);
}
var stores = ['.$myData.'];
function setMarkers(map) {
for (var i = 0; i < stores.length; i++) {
var store = stores[i];
var marker = new google.maps.Marker({
position: {lat: store[1], lng: store[2]},
map: map,
title: restaurant[0]
});
}
}
I need to re-center the map on map load. Should I try to average lat/lon coords from $myData array and replace center coords in initMap or is there a better way?
In this story: It's better to get average lat/long coordinates from the back-end (or calculate it on a front-end, but before you initialize a GoogleMap), so your map will be loaded in the right place and will not "tremble".
But you still may have a problem with zooming, and there are a few solutions. Most difficult is calculate again, but maybe you can try something of it (and it may make an interesting effect on page loading):
A. Zoom in from the space. Set smallest zoom and after google.API calculates bounding box — zoom in!
B. Show preloader screen over the map. In this case, you can calculate average lat/long using google.API too. It's the easiest way, but not so smooth and cool.
create an empty bounds object (a google.maps.LatLngBounds)
add all your markers to it
use it to center and zoom your map
function setMarkers(map) {
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < stores.length; i++) {
var store = stores[i];
var marker = new google.maps.Marker({
position: {lat: store[1], lng: store[2]},
map: map,
title: restaurant[0]
});
bounds.extend(marker.getPosition());
}
map.fitBounds(bounds);
}
code snippet:
function initMap() {
var map = new google.maps.Map(document.getElementById("map"), {
zoom: 12,
center: {
lat: 32.99999999,
lng: -95.2222328
}
});
setMarkers(map);
}
var stores = [
["store 1", 42, -72],
["store 2", 41, -74]
];
function setMarkers(map) {
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < stores.length; i++) {
var store = stores[i];
var marker = new google.maps.Marker({
position: {
lat: store[1],
lng: store[2]
},
map: map,
title: store[0]
});
bounds.extend(marker.getPosition());
}
map.fitBounds(bounds);
}
google.maps.event.addDomListener(window, "load", initMap);
html,
body,
#map {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map"></div>
Here is how I do it (a small snippet of my code) in jQuery, just pass your map into the function:
function (mapInfo) {
var noMarkers = false;
if (!mapInfo.markers || mapInfo.markers.length === 0) {
noMarkers = true;
var marker = new google.maps.Marker({
position: { lat: YOUR_DESIRED_HOME_POINT, lng: YOUR_DESIRED_HOME_POINT },
optimized: false
});
mapInfo.markers.push(marker);
}
var bounds = new google.maps.LatLngBounds();
// Create bounds from markers
$.each(mapInfo.markers, function (index, item) {
var latlng = mapInfo.markers[index].getPosition();
bounds.extend(latlng);
});
// Google wants to zoom ALL the way in for only one marker, so if there is only one, we'll back it out a bit
if (bounds.getNorthEast().equals(bounds.getSouthWest())) {
var adjustBy = noMarkers ? 20.5 : 0.005;
var extendNortheast = new google.maps.LatLng(bounds.getNorthEast().lat() + adjustBy, bounds.getNorthEast().lng() + adjustBy);
var extendSouthwest = new google.maps.LatLng(bounds.getNorthEast().lat() - adjustBy, bounds.getNorthEast().lng() - adjustBy);
bounds.extend(extendNortheast);
bounds.extend(extendSouthwest);
}
google.maps.event.addListenerOnce(mapInfo.map, 'bounds_changed', function () {
var zoom = mapInfo.map.getZoom();
if (zoom > 18) {
mapInfo.map.setZoom(16);
}
});
mapInfo.map.fitBounds(bounds);
}

Adding actionListeners to dynamically created google markers to plot routes

I have a page that retrieves some locations from a database and creates markers based on their lat/long to display on a map. The markers are saved in an array and I use a for loop to assign onclick action listeners to each marker. When the user clicks on a marker I want a route from their current location to the marker location to be displayed. The issue I am having is that regardless of which marker is clicked, it always plots a route to the final marker in the array.
This is what the map looks like
In the above example I am going to click the red marker A.
As you can see it has plotted a course to marker D.
My Code:
//THIS FUNCTIONS BUILD THE MAPS
function initializeMap(position)
{ //USER LOCATION
var myCenter = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
var mapProp =
{
center: myCenter,
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
mapObj = new google.maps.Map(document.getElementById("googleMap"), mapProp);
//MAKING SURE THE DATA ARRAY HAS SOMETHING IN IT
if (ajaxResult.length > 0)
{
for (var i = 0; i < ajaxResult.length; i++)
{
var pos = {lat: parseFloat(ajaxResult[i][6]), lng: parseFloat(ajaxResult[i][7])};
//BUILDING THE DESTINATION MARKERS
var suggestionMarker = new google.maps.Marker({
position: pos,
icon: markerNames[i]
});
markers.push(suggestionMarker);//ADDING TO THE MARKER ARRAY
suggestionMarker.setMap(mapObj);//ADING TO THE MAP
var userString = ajaxResult[i][1];//INFORMATINO WINDOW
var infowindow = new google.maps.InfoWindow({
content: userString
});
infowindow.open(mapObj, suggestionMarker);
}
addMarkerListeners(myCenter);
}
//MARKER FOR THE USER LOCATION
var userImage = 'assets/img/GoogleMapsMarkers/blue_MarkerA.png'
var userMarker = new google.maps.Marker({
position: myCenter,
icon: userImage
});
markers.push(userMarker);
userMarker.setMap(mapObj);
//USER INFORMATION WINDOW
var userString = "You!";
var infowindow = new google.maps.InfoWindow({
content: userString
});
infowindow.open(mapObj, userMarker);
}
/*
*
* #param {type} option
* #returns {Boolean}
* ACCEPTS THE USER LOCATION AND ADDS ACTION LISTENERS TO EACH MARKER
* IN THE MARKER ARRAY. THE ACTION LISTENER CALLS THE PLOT ROUTE
* FUNCTION AND PASSES IT THE MARKER POSITION AND USER POSITION
*/
function addMarkerListeners(myCenter)
{
if(markers.length > 0)
{
for(var i = 0; i < markers.length-1; i++)
{
google.maps.event.addListener(markers[i],'click', function(){plotRoute(markers[i].getPosition(),myCenter);});
//markers[i].addEventListener('click', function(){plotRoute(markers[i].getPosition(),myCenter);});
directionsDisplay.setMap(mapObj);
}
}
}
//CREATES A ROUT
function plotRoute(pos, myCenter)
{
var request = {
origin: myCenter,
destination: pos,
travelMode: 'DRIVING'
};
directionsService.route(request, function(result,status){
if(status === 'OK')
{
directionsDisplay.setDirections(result);
}
});
}
Note that the actual final marker is always the user marker but the for loop is instructed not to include it. Can anyone see why it only ever plots a route to the final destination marker in the marker array?
This is a common problem with loops setting up event listeners. It is solved in this related question: Google Maps JS API v3 - Simple Multiple Marker Example using function closure. To use that solution in your code:
function addMarkerListeners(myCenter) {
if (markers.length > 0) {
for (var i = 0; i < markers.length; i++) {
// function closure on the "i" variable
google.maps.event.addListener(markers[i], 'click', (function(i) {
return function() {
plotRoute(markers[i].getPosition(), myCenter);
}})(i));
directionsDisplay.setMap(mapObj);
}
}
}
proof of concept fiddle
To solve it without function closure, you could use the this inside the event handler function, which refers to the marker clicked:
function addMarkerListeners(myCenter) {
if (markers.length > 0) {
for (var i = 0; i < markers.length; i++) {
google.maps.event.addListener(markers[i], 'click', function() {
plotRoute(this.getPosition(), myCenter);
});
directionsDisplay.setMap(mapObj);
}
}
}
proof of concept fiddle
code snippet (using function closure):
var geocoder;
var map;
var markers = [];
var directionsDisplay = new google.maps.DirectionsRenderer();
var directionsService = new google.maps.DirectionsService();
function initialize() {
// Googleplex 37.4223434, -122.0843689
var position = {coords: {latitude:37.4223434, longitude:-122.0843689}}
initializeMap(position);
}
google.maps.event.addDomListener(window, "load", initialize);
// Menlo Park, CA, USA (37.4529598, -122.18172520000002)
// Mountain View, CA, USA (37.3860517, -122.0838511)
var ajaxResult = [[0,"infowindow 0",2,3,4,5,37.4419,-122.1419],
[1,"infowindow 1",2,3,4,5,37.4529598,-122.1817252],[2,"infowindow 2",2,3,4,5,37.3860517,-122.0838511]]
//THIS FUNCTIONS BUILD THE MAPS
function initializeMap(position) { //USER LOCATION
var myCenter = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
var mapProp = {
center: myCenter,
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
mapObj = new google.maps.Map(document.getElementById("googleMap"), mapProp);
//MAKING SURE THE DATA ARRAY HAS SOMETHING IN IT
if (ajaxResult.length > 0) {
for (var i = 0; i < ajaxResult.length; i++) {
var pos = {
lat: parseFloat(ajaxResult[i][6]),
lng: parseFloat(ajaxResult[i][7])
};
//BUILDING THE DESTINATION MARKERS
var suggestionMarker = new google.maps.Marker({
position: pos,
// icon: markerNames[i]
});
markers.push(suggestionMarker); //ADDING TO THE MARKER ARRAY
suggestionMarker.setMap(mapObj); //ADING TO THE MAP
var userString = ajaxResult[i][1]; //INFORMATINO WINDOW
var infowindow = new google.maps.InfoWindow({
content: userString
});
infowindow.open(mapObj, suggestionMarker);
}
addMarkerListeners(myCenter);
}
//MARKER FOR THE USER LOCATION
var userImage = 'http://maps.google.com/mapfiles/ms/micons/blue.png'
var userMarker = new google.maps.Marker({
position: myCenter,
icon: userImage
});
markers.push(userMarker);
userMarker.setMap(mapObj);
//USER INFORMATION WINDOW
var userString = "You!";
var infowindow = new google.maps.InfoWindow({
content: userString
});
infowindow.open(mapObj, userMarker);
}
/*
*
* #param {type} option
* #returns {Boolean}
* ACCEPTS THE USER LOCATION AND ADDS ACTION LISTENERS TO EACH MARKER
* IN THE MARKER ARRAY. THE ACTION LISTENER CALLS THE PLOT ROUTE
* FUNCTION AND PASSES IT THE MARKER POSITION AND USER POSITION
*/
function addMarkerListeners(myCenter) {
if (markers.length > 0) {
for (var i = 0; i < markers.length; i++) {
google.maps.event.addListener(markers[i], 'click', (function(i) {
return function() {
plotRoute(markers[i].getPosition(), myCenter);
}})(i));
directionsDisplay.setMap(mapObj);
}
}
}
//CREATES A ROUTE
function plotRoute(pos, myCenter) {
var request = {
origin: myCenter,
destination: pos,
travelMode: 'DRIVING'
};
directionsService.route(request, function(result, status) {
if (status === 'OK') {
directionsDisplay.setDirections(result);
} else alert("directions request failed: "+status);
});
}
html,
body,
#googleMap {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="googleMap"></div>
code snippet (using this):
var geocoder;
var map;
var markers = [];
var directionsDisplay = new google.maps.DirectionsRenderer();
var directionsService = new google.maps.DirectionsService();
function initialize() {
// Googleplex 37.4223434, -122.0843689
var position = {coords: {latitude:37.4223434, longitude:-122.0843689}}
initializeMap(position);
}
google.maps.event.addDomListener(window, "load", initialize);
// Menlo Park, CA, USA (37.4529598, -122.18172520000002)
// Mountain View, CA, USA (37.3860517, -122.0838511)
var ajaxResult = [[0,"infowindow 0",2,3,4,5,37.4419,-122.1419],
[1,"infowindow 1",2,3,4,5,37.4529598,-122.1817252],[2,"infowindow 2",2,3,4,5,37.3860517,-122.0838511]]
//THIS FUNCTIONS BUILD THE MAPS
function initializeMap(position) { //USER LOCATION
var myCenter = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
var mapProp = {
center: myCenter,
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
mapObj = new google.maps.Map(document.getElementById("googleMap"), mapProp);
//MAKING SURE THE DATA ARRAY HAS SOMETHING IN IT
if (ajaxResult.length > 0) {
for (var i = 0; i < ajaxResult.length; i++) {
var pos = {
lat: parseFloat(ajaxResult[i][6]),
lng: parseFloat(ajaxResult[i][7])
};
//BUILDING THE DESTINATION MARKERS
var suggestionMarker = new google.maps.Marker({
position: pos,
// icon: markerNames[i]
});
markers.push(suggestionMarker); //ADDING TO THE MARKER ARRAY
suggestionMarker.setMap(mapObj); //ADING TO THE MAP
var userString = ajaxResult[i][1]; //INFORMATINO WINDOW
var infowindow = new google.maps.InfoWindow({
content: userString
});
infowindow.open(mapObj, suggestionMarker);
}
addMarkerListeners(myCenter);
}
//MARKER FOR THE USER LOCATION
var userImage = 'http://maps.google.com/mapfiles/ms/micons/blue.png'
var userMarker = new google.maps.Marker({
position: myCenter,
icon: userImage
});
markers.push(userMarker);
userMarker.setMap(mapObj);
//USER INFORMATION WINDOW
var userString = "You!";
var infowindow = new google.maps.InfoWindow({
content: userString
});
infowindow.open(mapObj, userMarker);
}
/*
*
* #param {type} option
* #returns {Boolean}
* ACCEPTS THE USER LOCATION AND ADDS ACTION LISTENERS TO EACH MARKER
* IN THE MARKER ARRAY. THE ACTION LISTENER CALLS THE PLOT ROUTE
* FUNCTION AND PASSES IT THE MARKER POSITION AND USER POSITION
*/
function addMarkerListeners(myCenter) {
if (markers.length > 0) {
for (var i = 0; i < markers.length; i++) {
google.maps.event.addListener(markers[i], 'click', function() {
plotRoute(this.getPosition(), myCenter);
});
directionsDisplay.setMap(mapObj);
}
}
}
//CREATES A ROUT
function plotRoute(pos, myCenter) {
var request = {
origin: myCenter,
destination: pos,
travelMode: 'DRIVING'
};
directionsService.route(request, function(result, status) {
if (status === 'OK') {
directionsDisplay.setDirections(result);
}
});
}
html,
body,
#googleMap {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="googleMap"></div>

google maps v3: how to drop markers, remove, loop again

I have been studying Google Maps and I would like to accomplish the following goal:
1) drop markers one by one;
2) delete last marker (so just one is in viewport)
3) drop next marker
4) Have info window opened in each marker
5) repeat operation
I have been trying to twist the code for animations AND trying to set map null (setMap(null)), but with no success after calling the drop function. Any suggestion on how to do that?
Bottom line: have something like this. Of course this has one big extra step of difficult, which is pulling data from database.
Here is the code.
Any help will be greatly appreciated.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Marker animations with <code>setTimeout()</code></title>
<style>
#map-canvas{
width:600px;
height:600px;
position: "absolute";
top: 0px;
left: 0px;
overflow: "hidden";
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script>
var berlin = new google.maps.LatLng(52.520816, 13.410186);
var neighborhoods = [
new google.maps.LatLng(52.511467, 13.447179),
new google.maps.LatLng(52.549061, 13.422975),
new google.maps.LatLng(52.497622, 13.396110),
new google.maps.LatLng(52.517683, 13.394393)
];
var markers = [];
var iterator = 0;
var Marker;
var map;
function initialize() {
var mapOptions = {
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: berlin
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
drop();
}
function drop(){
for (var i = 0; i < neighborhoods.length; i++) {
var m = neighborhoods[i];
(function(n){
setTimeout(function() {
addMarker(n);
}, i * 500);
}(m));
}
}
function addMarker() {
markers.push(new google.maps.Marker({
position: neighborhoods[iterator],
map: map,
draggable: false,
animation: google.maps.Animation.DROP
}));
iterator++;
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas"></div>
</body>
</html
>
Did you want only one marker to display at a time?
Here is some code that does that:
$(function() {
var BERLIN = new google.maps.LatLng(52.520816, 13.410186);
var NEIGBORHOODS = [
new google.maps.LatLng(52.511467, 13.447179),
new google.maps.LatLng(52.549061, 13.422975),
new google.maps.LatLng(52.497622, 13.396110),
new google.maps.LatLng(52.517683, 13.394393)];
var map = null;
var marker = null;
var index = 0;
var infoWindow = null;
function createMap() {
return new google.maps.Map(document.getElementById('map-canvas'), {
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: BERLIN,
zoom: 12
});
}
function dropMarker(map, pos) {
return new google.maps.Marker({
map: map,
position: pos,
draggable: false,
animation: google.maps.Animation.DROP
});
}
function changeMarker() {
if (marker) {
infoWindow.close();
marker.setMap(null);
}
var pos = NEIGBORHOODS[index];
marker = dropMarker(map, pos);
infoWindow.setContent('lat: ' + pos.lat() + '<br />' + 'lng: ' + pos.lng());
setTimeout(function () {
infoWindow.open(map, marker);
}, 500);
index = (index + 1) % NEIGBORHOODS.length;
setTimeout(function () {
changeMarker();
}, 2000);
}
map = createMap();
infoWindow = new google.maps.InfoWindow()
changeMarker();
});
Notice how the changeMarker() function does its work, then usessetTimeout() to call itself again. This sets up an infinite loop where changeMarker() is called every two seconds.
I used setTimeout() to delay the showing of the Info Window by a half second so it does not appear until the drop is finished.
jsfiddle demo

Categories

Resources