How to add weather layer to the current infowindow Google Map? - javascript

I want to add this forecast to the infowindow. I wanna use Google weather layers. But i dont know how to put them to the current infowindow
var weatherLayer = new google.maps.weather.WeatherLayer({
temperatureUnits: google.maps.weather.TemperatureUnit.FAHRENHEIT
});
var cloudLayer = new google.maps.weather.CloudLayer();
How can i add forecast to the current info window, after details of location?
Thank you
function showPosition(position) {
var googlePos = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
var mapOptions = {
zoom: 12,
center: googlePos,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var mapObj = document.getElementById('divmap');
var googleMap = new google.maps.Map(mapObj, mapOptions);
var markerOpt = {
map: googleMap,
position: googlePos,
title: 'Hi , I am here',
animation: google.maps.Animation.DROP
};
var googleMarker = new google.maps.Marker(markerOpt);
var geocoder = new google.maps.Geocoder();
geocoder.geocode({
'latLng': googlePos
}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
var popOpts = {
content: results[1].formatted_address,
position: googlePos
};
var popup = new google.maps.InfoWindow(popOpts);
/*google.maps.event.addListener(googleMap, 'center_changed', function(){
window.setTimeout(function(){
googleMap.panTo(googleMarker.getPosition());
}, 2000);
});*/
google.maps.event.addListener(googleMarker, 'setTimeout', setTimeout(function () {
popup.open(googleMap, googleMarker)
}, 200));
} else {
alert('No results found');
}
} else {
alert('Geocoder failed due to: ' + status);
}
});
}

Related

Clear Marker on Google Map when change location of dropdown

all. Please help me solve this issue. Currently I have a dropdown of multiple location for google map. But the marker keeps on duplicating when I change the location. Here is the code for google map. I would like the map to clear the previous marker and only display marker on the current selected location
var geocoder;
var map;
var marker;
function initMap() {
var mapCanvas = document.getElementById("map");
var mapOptions = {
center: new google.maps.LatLng(4.2105,101.9758),
zoom: 6.5
};
map = new google.maps.Map(mapCanvas, mapOptions);
geocoder = new google.maps.Geocoder();
google.maps.event.addDomListener(window, "load", initMap);
}
function geocodeAddress(location) {
var address = '';
if (location != 'all') {
var resultFromAjax = $.ajax({
type: 'POST',
url: "{{ route('getLocation') }}",
data: {
id: location
},
success: function (response) {
if (response.location != '') {
address = response.location;
}
},
error: function (xhr) {
console.log(xhr);
},
async: false
});
}
else {
address = 'Malaysia';
}
geocoder = new google.maps.Geocoder();
geocoder.geocode({'address': address}, function(results, status) {
if (status === 'OK') {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
animation: google.maps.Animation.DROP,
position: results[0].geometry.location
});
console.log(marker)
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
</script>
I have found the solution, instead of locally declare the marker, I set it as a global function before populate it based on location using geocoding.
var geocoder;
var map;
var marker;
function initMap() {
var mapCanvas = document.getElementById("map");
var mapOptions = {
center: new google.maps.LatLng(4.2105,101.9758),
zoom: 6.5
};
map = new google.maps.Map(mapCanvas, mapOptions);
geocoder = new google.maps.Geocoder();
//Marker
marker = new google.maps.Marker();
marker.setPosition(map.getCenter());
marker.setMap(map);
//
google.maps.event.addDomListener(window, "load", initMap);
}
function geocodeAddress(location) {
var address = '';
if (location != 'all') {
var resultFromAjax = $.ajax({
type: 'POST',
url: "{{ route('getLocation') }}",
data: {
id: location
},
success: function (response) {
if (response.location != '') {
address = response.location;
}
},
error: function (xhr) {
console.log(xhr);
},
async: false
});
}
else {
address = 'Malaysia';
}
geocoder = new google.maps.Geocoder();
geocoder.geocode({'address': address}, function(results, status) {
if (status === 'OK') {
map.setCenter(results[0].geometry.location);
marker.setOptions({
map: map,
animation: google.maps.Animation.DROP,
position: results[0].geometry.location
});
// var marker = new google.maps.Marker({
// map: map,
// animation: google.maps.Animation.DROP,
// position: results[0].geometry.location
// });
console.log(marker)
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}

google maps user location not loading

I can create a webpage that takes the name, address, lat and long of many businesses in a specific city and have put them into an embedded google map on my page. The connection to the database works, putting up the markers on the map works, however what I can't figure out from any examples, including those on Googles developers page, is how to user a user's location instead of the default coord in the googlemap.js file. What am I missing here?
var map;
var geocoder;
function loadMap() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition((position) => {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
map = new google.maps.Map(document.getElementById('map'),
{
zoom: 14,
center: pos
});
});
}
var marker = new google.maps.Marker({
// position: pune,
map: map
});
var cdata = JSON.parse(document.getElementById('data').innerHTML);
geocoder = new google.maps.Geocoder();
codeAddress(cdata);
var allData = JSON.parse(document.getElementById('allData').innerHTML);
showAllHonda(allData)
}
function showAllHonda(allData) {
var infoWind = new google.maps.InfoWindow;
Array.prototype.forEach.call(allData, function(data){
var content = document.createElement('div');
var strong = document.createElement('strong');
strong.textContent = data.name;
content.appendChild(strong);
var marker = new google.maps.Marker({
position: new google.maps.LatLng(data.lat, data.lng),
map: map
});
marker.addListener('click', function(){
infoWind.setContent(content);
infoWind.open(map, marker);
})
})
}
function codeAddress(cdata) {
Array.prototype.forEach.call(cdata, function(data){
var address = data.name + ' ' + data.address;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == 'OK') {
map.setCenter(results[0].geometry.location);
var points = {};
points.id = data.id;
points.lat = map.getCenter().lat();
points.lng = map.getCenter().lng();
updateHondaWithLatLng(points);
} else {
alert('Geocode was not successful for the following reason: ' + status)
}
});
});
}
To find user's position you can use navigator.geolocation :
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition((position) => {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
map = new google.maps.Map(document.getElementById('map'),
{
zoom: 14,
center: pos
});
});
}

Working with two google maps

Hi I need some help with the following:
I am trying to get two maps to display two different things.
My problem is, on the first map I would like to click on a link in the infowindow (see this) when I do click on that link, I would like that marker to display alone on the second map at its location.
here is my code. Thank you for any help.
$(document).ready(function() {
var map;
var service;
function initialise(location) {
console.log("location:" + location);
var currentLocation = new google.maps.LatLng(location.coords.latitude, location.coords.longitude);
var mapOption = {
center : currentLocation,
zoom : 14,
mapTypeId : google.maps.MapTypeId.ROADMAP,
};
map = new google.maps.Map(document.getElementById("map-canvas"), mapOption);
var marker = new google.maps.Marker({
position : currentLocation,
map : map,
});
marker.setIcon('http://maps.google.com/mapfiles/ms/icons/green-dot.png');
//service = new google.maps.places.PlacesService(map);
google.maps.event.addListenerOnce(map, 'bounds_changed', performSearch);
function handleSearchResults(results, status) {
console.log(results)
}
function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
}
}
}
function createMarker(place) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map : map,
position : place.geometry.location
});
var content = '<p>See this</p>'
var infowindow = new google.maps.InfoWindow({
content:('<div><strong>' + place.name + '</strong><br>' +
'Place ID: ' + place.place_id + '<br>' +
place.formatted_address + content)
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map, marker);
var latitude = this.position.lat();
var longitude = this.position.lng();
console.log(this.position);
});
}
google.maps.event.addListenerOnce(map, 'bounds_changed', function() {
var input = $("#search").val();
var query = (input != '' )? input : "restaurant";
performSearch(query);
});
function performSearch(q){
var request ={
bounds: map.getBounds(),
query:String(q)
};
service.textSearch(request, callback);
}
}
function initializer() {
map = new google.maps.Map(document.getElementById('map-canvas'), {
zoom: 13,
});
if(navigator.geolocation) {
browserSupportFlag = true;
navigator.geolocation.getCurrentPosition(function(position) {
initialLocation = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
map.setCenter(initialLocation);
var marker = new google.maps.Marker({
position : initialLocation,
map : map,
});
marker.setIcon('http://maps.google.com/mapfiles/ms/icons/green-dot.png');
}, function() {
handleNoGeolocation(browserSupportFlag);
});
}
}
function initializer_2() {
var mapOption2 = {
center : new google.maps.LatLng(41.923, 12.513),
zoom : 14,
mapTypeId : google.maps.MapTypeId.ROADMAP,
};
var marker = new google.maps.Marker({
// need the position of marker
//position : currentLocation,
map : map,
});
map = new google.maps.Map(document.getElementById("map-canvas2"), mapOption2);
}
google.maps.event.addDomListener(window, 'load', initializer);
google.maps.event.addDomListener(window, 'load', initializer_2);
$(".getSearch").click(function () {
navigator.geolocation.getCurrentPosition(initialise);
});
});

how to get center latitude and longitude in route between two location

I am using google map to find route between two location.i want to get center latitude and longitude of the route. can u please tell me how to get center of the route.i am using the below code for getting routes,Thanks in advance
var map;
var directionsDisplay;
var directionsService;
var stepDisplay;
var markerArray = [];
var infoWindow;
var service;
var lat1 = 0;
var lng1;
function pre_initialize() {
var mapOptions = {
zoom: 6,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
var pos = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
var infowindow = new google.maps.InfoWindow({
map: map,
position: pos,
content: 'Current Location.'
});
map.setCenter(pos);
}, function () {
handleNoGeolocation(true);
});
} else {
// Browser doesn't support Geolocation
handleNoGeolocation(false);
}
}
function handleNoGeolocation(errorFlag) {
if (errorFlag) {
var content = 'Error: The Geolocation service failed.';
} else {
var content = 'Error: Your browser doesn\'t support geolocation.';
}
var options = {
map: map,
position: new google.maps.LatLng(60, 105),
content: content
};
var infowindow = new google.maps.InfoWindow(options);
map.setCenter(options.position);
}
function initialize() {
var mapOptions = {
zoom: 6,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
var addressfrom = document.getElementById("from").value;
var addressto = document.getElementById("to").value;
var geocoder = new google.maps.Geocoder();
var coords = new google.maps.LatLng(0, 0);
alert(lat1);
coords = geocoder.geocode({ 'address': addressfrom }, function (results, status) {
results[0].geometry.location.lat();
results[0].geometry.location.lng();
});
directionsService = new google.maps.DirectionsService();
// Create a renderer for directions and bind it to the map.
var rendererOptions = {
map: map
}
directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions)
// Instantiate an info window to hold step text.
infoWindow = new google.maps.InfoWindow();
stepDisplay = new google.maps.InfoWindow();
calcRoute();
google.maps.event.addListenerOnce(map, 'bounds_changed', performSearch);
}
function performSearch() {
var request = {
bounds: map.getBounds(),
radius: 100,
types: ['hospital', 'cafe', 'restaurant', 'food', 'bar'],
keyword: 'best view'
};
service = new google.maps.places.PlacesService(map);
//service.nearbySearch(request, callback);
service.radarSearch(request, callback);
//service.textSearch(request, callback);
}
function callback(results, status) {
if (status != google.maps.places.PlacesServiceStatus.OK) {
alert(status);
return;
}
for (var i = 0, result; result = results[i]; i++) {
createMarker(result);
}
}
function createMarker(place) {
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location,
icon:
{
// Star
path: 'M 0,-24 6,-7 24,-7 10,4 15,21 0,11 -15,21 -10,4 -24,-7 -6,-7 z',
fillColor: '#ff0000',
fillOpacity: 1,
scale: 1 / 4,
strokeColor: '#bd8d2c',
strokeWeight: 1
}
});
google.maps.event.addListener(marker, 'click', function () {
service.getDetails(place, function (result, status) {
if (status != google.maps.places.PlacesServiceStatus.OK) {
alert(status);
return;
}
infoWindow.setContent(result.name);
infoWindow.open(map, marker);
});
});
}
function calcRoute() {
// First, remove any existing markers from the map.
for (var i = 0; i < markerArray.length; i++) {
markerArray[i].setMap(null);
}
// Now, clear the array itself.
markerArray = [];
var start = document.getElementById('from').value;
var end = document.getElementById('to').value;
var request = {
origin: start,
destination: end,
travelMode: google.maps.TravelMode.WALKING
};
directionsService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
var warnings = document.getElementById('warnings_panel');
warnings.innerHTML = '<b>' + response.routes[0].warnings + '</b>';
directionsDisplay.setDirections(response);
showSteps(response);
}
});
}
function showSteps(directionResult) {
var myRoute = directionResult.routes[0].legs[0];
for (var i = 0; i < myRoute.steps.length; i++) {
var marker = new google.maps.Marker({
position: myRoute.steps[i].start_point,
map: map
});
attachInstructionText(marker, myRoute.steps[i].instructions);
markerArray[i] = marker;
}
}
function attachInstructionText(marker, text) {
google.maps.event.addListener(marker, 'click', function () {
stepDisplay.setContent(text);
stepDisplay.open(map, marker);
});
}
</script>
Refer to the code below:
self.adjustPosition = function () {
var lat = 0, lng = 0;
if (self.nearbyPlaces().length == 0) {
return false;
}
for (var i = 0; i < self.nearbyPlaces().length; i++) {
lat += self.nearbyPlaces()[i].latitude;
lng += self.nearbyPlaces()[i].longitude;
}
lat = lat / self.nearbyPlaces().length;
lng = lng / self.nearbyPlaces().length;
self.map.setCenter(new window.google.maps.LatLng(lat, lng));
};

How to edit default marker in google maps

Kindly check this map view: http://gmaps-samples-v3.googlecode.com/svn/trunk/map_language/map_lang.html
If you click on A or B, it will show location name in default marker. I wish to show some custom texts here. How can I do that?
My JavaScript code for this is:
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
var oldDirections = [];
var currentDirections = null;
//getting latitude and longitude from address
var latitude;
var longitude;
var geocoder = new google.maps.Geocoder();
var address = "Downtown Berkeley";
geocoder.geocode( { "address": address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK)
{
// do something with the geocoded result
//
latitude = results[0].geometry.location.lat()
longitude = results[0].geometry.location.lng()
alert(latitude )
}
});
//map initialize
function initialize() {
var myOptions = {
zoom: 13,
center: new google.maps.LatLng(-33.879,151.235),
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
//adding marker
var marker = new google.maps.Marker
(
{
position: new google.maps.LatLng(latitude , longitude),
map: map,
title: "Click me"
}
);
var infowindow = new google.maps.InfoWindow({
content: "Location info:<br/>Country Name:<br/>LatLng:"
});
google.maps.event.addListener(marker, "click", function () {
// Calling the open method of the infoWindow
infowindow.open(map, marker);
});
directionsDisplay = new google.maps.DirectionsRenderer({
"map": map,
"preserveViewport": true,
"draggable": true
});
directionsDisplay.setPanel(document.getElementById("directions_panel"));
google.maps.event.addListener(directionsDisplay, "directions_changed",
function() {
if (currentDirections) {
oldDirections.push(currentDirections);
}
currentDirections = directionsDisplay.getDirections();
});
calcRoute();
}
function calcRoute() {
var start = "El Cerrito del Norte";
var end = "Downtown Berkeley";
var request = {
origin:start,
destination:end,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
You set that content in the createInfoWindow() method.

Categories

Resources