I have two locations (markers) to display on a google map, one is a static variable called "companyLocale". The second is a dynamic variable based on your current location "initialLocation". I am trying to group them into an array called "localArray" but I can't get the "companyLocale" variable to display within the array . Can someone please help me?
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Google Maps JavaScript API v3 Example: iPhone Geolocation</title>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var initialLocation;
var companyLocale = new google.maps.LatLng(33.206060, -117.111951);
var localArray = [initialLocation,companyLocale];
var noGeo = new google.maps.LatLng(40.69847032728747, -73.9514422416687);
function initialize() {
var myOptions = {
zoom: 14,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
// Safari supports the W3C Geolocation method
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
initialLocation = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
var placeMarker = new google.maps.Marker({
position: initialLocation,
map: map,
});
map.setCenter(initialLocation);
}, function() {
handleNoGeolocation(browserSupportFlag);
});
} else {
// Browser doesn't support Geolocation
handleNoGeolocation();
}
function handleNoGeolocation() {
initialLocation = noGeo;
map.setCenter(initialLocation);
}
}
</script>
</head>
<body style="margin:0px; padding:0px;" onload="initialize()">
<div id="map_canvas" style="width:100%; height:100%"></div>
</body>
</html>
You're populating localArray with the two values before your initialize function gets called. As you've already defined companyLocale as a LatLng, that one is fine, but you don't create the initialLocation LatLng until later in your execution.
I would say remove initialLocation from the array initially. Then after you create it, add it into the array. I don't know if the order of the array items is important here for you or not. If it isn't, just use .push() to append it into the array. Otherwise use unshift() to prepend it.
<script type="text/javascript">
var initialLocation;
var companyLocale = new google.maps.LatLng(33.206060, -117.111951);
var localArray = [companyLocale];
var noGeo = new google.maps.LatLng(40.69847032728747, -73.9514422416687);
function initialize() {
var myOptions = {
zoom: 14,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
// Safari supports the W3C Geolocation method
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
initialLocation = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
localArray.unshift(initialLocation);
var placeMarker = new google.maps.Marker({
position: initialLocation,
map: map,
});
map.setCenter(initialLocation);
}, function() {
handleNoGeolocation(browserSupportFlag);
});
} else {
// Browser doesn't support Geolocation
handleNoGeolocation();
}
function handleNoGeolocation() {
initialLocation = noGeo;
localArray.unshift(initialLocation );
map.setCenter(initialLocation);
}
}
</script>
Related
I'm trying to create a multiple markers map. Every marker will have his infoWindow. I followed all the dev GoogleMaps information and infoWindow are still not appearing.
In this code that I'll give to you, I only create 3 markers with my own function "PintaMarker". This function creates a marker and adds its listener with the infowindow information and pushes the marker to my "markers Array" called markers.
When I finish the creation of the markers, I generate a MarkerClusterer to use and see all markers I create.
Can anyone take a look at my code and give me a hand on it?
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="ca" lang="ca">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Markers Map</title>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<!--script src="js/bootstrap.js"></script-->
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript" src="http://google-maps-utility-library-v3.googlecode.com/svn/trunk/markerclusterer/src/markerclusterer_compiled.js"></script>
</head>
<body>
<div id="map1" style="width:100%; height: 913px"></div>
</body>
<script>
var markers = [];
var map1=null;
var geocoder;
var infowindow = new google.maps.InfoWindow();
function pintaMarker(lat,lng,html){
var myLatLng = new google.maps.LatLng(lat, lng);
var marker = new google.maps.Marker({
position: myLatLng,
map: map1,
});
google.maps.event.addListener(marker, 'click', function(){
infowindow.setOptions({
content: html
});
infowindow.open(map1,marker);
console.log(infowindow);
});
markers.push(marker);
}
$(document).ready(function() {
//var center = new google.maps.LatLng(41.644183,1.620483);
geocoder = new google.maps.Geocoder();
var center = new google.maps.LatLng(41.38257066,2.15659028);
var options = {
zoom: 16,
center: center,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map1 = new google.maps.Map(document.getElementById("map1"), options);
pintaMarker(41.385, 2.154, 'hola');
pintaMarker(41.387, 2.1529, 'hola2');
pintaMarker(41.38254, 2.1562, 'hola3');
var markerCluster = new MarkerClusterer(map1, markers);
});
</script>
</html>
Thank you!
The porblem ist that in your function pintaMarkerthe map1 object is null!!
The solution:
Pass the map object as a parameter to your pintaMarker like this:
pintaMarker(41.385, 2.154, 'hola', map1);
and update you function to:
function pintaMarker(lat,lng,html, map1){
var myLatLng = new google.maps.LatLng(lat, lng);
var marker = new google.maps.Marker({
position: myLatLng,
map: map1,
});
google.maps.event.addListener(marker, 'click', function(){
infowindow.setOptions({
content: html
});
infowindow.open(map1, marker);
console.log(infowindow);
});
markers.push(marker);
}
now the map object is available!
I've looked through the answers for other questions similar to mine, but I'm still unable to get my code to work. Right now, I'm simply trying to add a toggle on/off button for the weather layer on the map. However, nothing happens when I click the button, and I'm not sure where I'm going wrong.
<script type="text/javascript">
// Declaring the map as a global variable
var map;
function initialize() {
var latlng = new google.maps.LatLng(27.7428, -97.4019);
var weatherOn = false; //starts off false because the weather layer is not on by default
// Setting up the map options
var mapOptions = {
center: latlng,
zoom: 5,
mapTypeId: google.maps.MapTypeId.ROADMAP,
backgroundColor:'#c0c0c0',
draggableCursor: 'pointer',
draggingCursor: 'crosshair'
};
// Assigning map to its variable
map = new google.maps.Map(document.getElementById("map-canvas"),
mapOptions);
var weatherLayer = new google.maps.weather.WeatherLayer({
temperatureUnits: google.maps.weather.TemperatureUnit.FAHRENHEIT
});
// weatherLayer.setMap(map);
// Setting a listener that will toggle the weather layer
google.maps.event.addDomListener(document.getElementById("weatherToggle"), 'click', function() {
if ( weatherOn == true ) {
weatherLayer.setMap(null);
weatherOn = false;
}
else {
weatherLayer.setMap(map);
weatherOn = true;
}
});
};
</script>
weatherToggle is the id for the button that I created on my page. Thanks for the help!
Are you including the weather library? This code works for me:
<!DOCTYPE html>
<html>
<head>
<title>Google Maps</title>
<style type="text/css">
html, body, #map-canvas {
width: 100%;
height: 500px;
margin: 0px;
padding: 0px
}
</style>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3&sensor=false&libraries=weather">
</script>
<script type="text/javascript">
// Declaring the map as a global variable
var map;
function initialize() {
var latlng = new google.maps.LatLng(27.7428, -97.4019);
var weatherOn = false; //starts off false because the weather layer is not on by default
// Setting up the map options
var mapOptions = {
center: latlng,
zoom: 5,
mapTypeId: google.maps.MapTypeId.ROADMAP,
backgroundColor:'#c0c0c0',
draggableCursor: 'pointer',
draggingCursor: 'crosshair'
};
// Assigning map to its variable
map = new google.maps.Map(document.getElementById("map-canvas"),
mapOptions);
var weatherLayer = new google.maps.weather.WeatherLayer({
temperatureUnits: google.maps.weather.TemperatureUnit.FAHRENHEIT
});
// weatherLayer.setMap(map);
// Setting a listener that will toggle the weather layer
google.maps.event.addDomListener(document.getElementById("weatherToggle"), 'click', function() {
if ( weatherLayer.getMap() != null ) {
weatherLayer.setMap(null);
}
else {
weatherLayer.setMap(map);
}
});
};
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<input type="button" id="weatherToggle" value="toggle"></input>
<div id="map-canvas"></div>
</body>
</html>
working example
Here is my code:
<!DOCTYPE html>
<html>
<head>
<title>Simple Map</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<style>
html, body, #map-canvas {
margin: 0;
padding: 0;
height: 100%;
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script>
var map;
function initialize() {
var mapOptions = {
zoom: 8,
center: new google.maps.LatLng(-34.397, 150.644),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
}
google.maps.event.addDomListener(window, 'load', initialize);
function displayRoute() {
var start = new google.maps.LatLng(28.694004, 77.110291);
var end = new google.maps.LatLng(28.72082, 77.107241);
var directionsDisplay = new google.maps.DirectionsRenderer();// also, constructor can get "DirectionsRendererOptions" object
directionsDisplay.setMap(map); // map should be already initialized.
var request = {
origin : start,
destination : end,
travelMode : google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
</script>
</head>
<body onload="displayRoute">
<div id="map-canvas"></div>
</body>
</html>
Why is this not working???
I am simply trying to NOT have the user input the two coordinates, I want to predefine those and just have a map with a route drawn on it. Ideally I just want a line, I don't want directions or anything.
Bottom line: I simply want to highlight the road between two given points.
You need to create an instance of the DirectionsService:
var map;
var directionsService = new google.maps.DirectionsService();
Also the onload should be onload="displayRoute()"
My Google map works okay but the mouseover and mouseout are not showing the div. Can anyone see my mistake or what I have done wrong? I have jquery installed on my host server.
<html>
<head>
<title>Map</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<script src="jquery/jquery.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script type="text/javascript">
function initialize() {
var LatLng = new google.maps.LatLng(51.620946, -8.890981);
var mapOptions = {
zoom: 12,
center: LatLng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
var contentstring = '<div style="height:50px;background-color:red;width:50px;">Hello</div>';
var LatLng = new google.maps.LatLng(51.620946, -8.890981);
var marker_0 = new google.maps.Marker({
position:LatLng,
map:map,
descrip:contentstring,
link:'https://www.google.ie/'
})
google.maps.event.addListener(marker_0,'mouseover',function(){
tooltip.show(this.descrip);
});
google.maps.event.addListener(marker_0,'mouseout',function(){
tooltip.hide();
});
google.maps.event.addListener(marker_0,'click',function(){
window.open(this.link);
});
}
$(document).ready(function(){
initialize();
})
</script>
</head>
<body>
<div id="map-canvas" style="width:600px;height:400px;border:solid 1px red;"></div>
</body>
</html>
Thanks in advance for any help.
From the code above, It doesn't look like you have defined the variable 'tooltip'
Instead of passing descrip and link properties to your marker_0, try just passing the title and it works. Like this...
function initialize() {
var LatLng = new google.maps.LatLng(51.620946, -8.890981);
var mapOptions = {
zoom: 12,
center: LatLng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
var contentstring = '<div style="height:50px;background-color:red;width:50px;">Hello</div>';
var marker_0 = new google.maps.Marker({
position:LatLng,
map:map,
title: contentstring
//descrip:contentstring,
//link:'https://www.google.ie/'
})
/*
** HAVE COMMENTED THIS BIT OUT AS THE MARKER ABOVE WILL WORK AS A TOOL TIP **
google.maps.event.addListener(marker_0,'mouseover',function(){
tooltip.show(this.descrip);
});
google.maps.event.addListener(marker_0,'mouseout',function(){
tooltip.hide();
});
google.maps.event.addListener(marker_0,'click',function(){
window.open(this.link);
}); */
}
There is a Simple Marker Exmaple Here
The properties that can be used for the marker is listes in the DOCS.
Hope this helps.
I am writing JavaScript code using Google Maps API.
map = new google.maps.Map2(document.getElementById("map_canvas"));
map.setCenter(new google.maps.LatLng(37.4419, -122.1419), 13);
The above code sets the default location of the map canvas to Palo Alto.
How can we write the script in such a way that the setCenter function automatically points to the current location of the client?
You can use the HTML5 GeoLocation API in browsers that support it.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(success, error);
} else {
alert('geolocation not supported');
}
function success(position) {
alert(position.coords.latitude + ', ' + position.coords.longitude);
}
function error(msg) {
alert('error: ' + msg);
}
I can think of two possible options.
First you may want to consider using the GeoLocation API as ceejayoz suggested. This is very easy to implement, and it is a fully client-side solution. To center the map using GeoLocation, simply use:
map.setCenter(new google.maps.LatLng(position.coords.latitude,
position.coords.longitude), 13);
... inside the success() callback of the GeoLocation's getCurrentPosition() method.
Unfortunately only a few modern browsers are currently supporting the GeoLocation API. Therefore you can also consider using a server-side solution to resolve the IP address of the client into the user's location, using a service such as MaxMind's GeoLite City. Then you can simply geocode the city and country of the user inside the browser, using the Google Maps API. The following could be a brief example:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Google Maps API Geocoding Demo</title>
<script src="http://maps.google.com/maps?file=api&v=2&sensor=false"
type="text/javascript"></script>
</head>
<body onunload="GUnload()">
<div id="map_canvas" style="width: 400px; height: 300px"></div>
<script type="text/javascript">
var userLocation = 'London, UK';
if (GBrowserIsCompatible()) {
var geocoder = new GClientGeocoder();
geocoder.getLocations(userLocation, function (locations) {
if (locations.Placemark) {
var north = locations.Placemark[0].ExtendedData.LatLonBox.north;
var south = locations.Placemark[0].ExtendedData.LatLonBox.south;
var east = locations.Placemark[0].ExtendedData.LatLonBox.east;
var west = locations.Placemark[0].ExtendedData.LatLonBox.west;
var bounds = new GLatLngBounds(new GLatLng(south, west),
new GLatLng(north, east));
var map = new GMap2(document.getElementById("map_canvas"));
map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
map.addOverlay(new GMarker(bounds.getCenter()));
}
});
}
</script>
</body>
</html>
Simply replace userLocation = 'London, UK' with the server-side resolved address. The following is a screenshot from the above example:
You can remove the marker by getting rid of the map.addOverlay(new GMarker(bounds.getCenter())); line.
that already exists in the google api:
if (GBrowserIsCompatible())
{
var map = new google.maps.Map2(document.getElementById("mapdiv"));
if (google.loader.ClientLocation)
{
var center = new google.maps.LatLng(
google.loader.ClientLocation.latitude,
google.loader.ClientLocation.longitude
);
var zoom = 8;
map.setCenter(center, zoom);
}
}
There are several threads with the same question...
This solution tries to get user location from browser first,
if the user refused or any other error occurs it then gets the location from user's IP address
mapUserLocation = () => {
navigator.geolocation
? navigator.geolocation.getCurrentPosition(
handlePosition,
getLocationFromIP
)
: getLocationFromIP();
};
getLocationFromIP = () => {
fetch("http://ip-api.com/json")
.then(response => response.json())
.then(data => {
data.lat &&
data.lon &&
updateUserPosition({
lat: data.lat,
lng: data.lon
});
})
.catch(error => {
console.log(`Request failed: `, error);
});
};
handlePosition = position => {
const userPos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
updateUserPosition(userPos);
};
updateUserPosition = position => {
map.setCenter(position, 13);
};
and call it like:
mapUserLocation();
An updated version of #ceejayoz's answer:
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(success, error);
} else {
alert('geolocation not supported');
}
function error(msg) {
alert('error: ' + msg);
}
function success(position) {
var myLatlng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
var mapOptions = {
zoom: 12,
center: myLatlng,
scaleControl: false,
draggable: false,
scrollwheel: false,
navigationControl: false,
mapTypeControl: false
}
map = new google.maps.Map(document.getElementsByClassName('map-canvas')[0], mapOptions);
marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: 'Main map',
icon: iconBase + 'arrow.png'
});
}
map = new google.maps.Map2(document.getElementById("map_canvas"));
pos = new google.maps.LatLng(37.4419, -122.1419);
map.setCenter(pos, 13);
map.panTo(pos);
Try this bro : I centered Indonesia using lat and lng.
$(document).ready(function () {
var mapOptions = {
zoom: 4,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map'), mapOptions);
var center = new google.maps.LatLng(-2.548926, 118.0148634);
map.setCenter(center,4);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://maps.googleapis.com/maps/api/js?libraries=places&sensor=false"></script>
<div id="map" style="width:600px; height:450px"></div>