For some reason my google maps is only loading, after I refresh the page. I already tried a some fixes, but they haven't worked for me.
I already added
$(document).ready(function() {
initMap();
});
$(document).bind("projectLoadComplete", initMap);
to my code, but it doesn't fix the problem.
Some guys also use google.maps.event.addDomListener(window, 'load', initialize); instead of $(document).ready(function() {initMap();}); but then I get the error: "Google is not defined".
Here's the full HTML Code without css:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Marker</title>
<link href="https://fonts.googleapis.com/css2?family=Raleway&display=swap" rel="stylesheet">
<script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script type="text/javascript">
function initMap() {
window.onmessage = (event) => {
if (event.data) {
const map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(48.68933623258264, 11.05938929396435),
zoom: 5,
streetViewControl: false,
fullscreenControl: true,
zoomControl: true,
});
const input = document.getElementById("pac-input");
const autocomplete = new google.maps.places.Autocomplete(input);
autocomplete.setComponentRestrictions({
country: ["de", "ch", "at", "it", "lie"]
});
autocomplete.bindTo("bounds", map);
var markerIcon = {
url: "https://static.wixstatic.com/media/c4g8dl_c2fd4dfd9ce72ede7acb9e44~mv2.png",
size: new google.maps.Size(22, 35),
origin: new google.maps.Point(0, 0),
scaledSize: new google.maps.Size(22, 35)
};
autocomplete.setFields(["place_id", "formatted_address", "geometry", "name"]);
const infowindow = new google.maps.InfoWindow();
const infowindowContent = document.getElementById("infowindow-content");
infowindow.setContent(infowindowContent);
const marker = new google.maps.Marker({
map: map,
icon: markerIcon
});
marker.addListener("click", () => {
infowindow.open(map, marker);
});
autocomplete.addListener("place_changed", () => {
infowindow.close();
const place = autocomplete.getPlace();
if (!place.geometry || !place.geometry.location) {
return;
}
if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
} else {
map.setCenter(place.geometry.location);
map.setZoom(17);
}
marker.setPlace({
placeId: place.place_id,
location: place.geometry.location,
});
marker.setVisible(true);
infowindowContent.children.namedItem("place-name").textContent = place.name;
infowindowContent.children.namedItem("place-address").textContent = place.formatted_address;
infowindow.open(map, marker);
window.parent.postMessage([place.name, place.formatted_address, place.geometry.location.lat(), place.geometry.location.lng()], "*");
});
}
}
}
function ready() {
window.parent.postMessage({
"type": "ready"
}, "*");
}
$(document).ready(function() {
initMap();
});
$(document).bind("projectLoadComplete", initMap);
</script>
</head>
<body onload="ready()">
<div id="input">
<input id="pac-input" class="controls" type="text" placeholder="adress">
</div>
<div id="map"></div>
<div id="infowindow-content">
<span id="place-name" class="title"></span><br />
<span id="place-address"></span><br />
</div>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=MY_KEY&callback=initMap&libraries=places&v=weekly" async defer></script>
</body>
</html>
Edit: If I open the page with my Map in a new Tab, the map is loading. The error just occurs, if I open the page in the same tab.
Maybe my website doesn't fire the full code of my iFrame.
I fixed the issue. The problem was the window.onmessage = (event) => {.
I think the map couldn't load, because the callback runs before the map receives an onmessage event.
I used the code from another map I created, so I just deleted the onmessage part, because I only need to send some data to my website and not from my website to my html.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Marker</title>
<link href="https://fonts.googleapis.com/css2?family=Raleway&display=swap" rel="stylesheet">
<script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
<script type="text/javascript">
function initMap() {
const map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(48.68933623258264, 11.05938929396435),
zoom: 5,
streetViewControl: false,
fullscreenControl: true,
zoomControl: true,
});
const input = document.getElementById("pac-input");
const autocomplete = new google.maps.places.Autocomplete(input);
autocomplete.setComponentRestrictions({
country: ["de", "ch", "at", "it", "lie"]
});
autocomplete.bindTo("bounds", map);
var markerIcon = {
url: "https://static.wixstatic.com/media/e6dc2fd4dfd9ce72ede7acb9e44~mv2.png",
size: new google.maps.Size(22, 35),
origin: new google.maps.Point(0, 0),
scaledSize: new google.maps.Size(22, 35)
};
autocomplete.setFields(["place_id", "formatted_address", "geometry", "name"]);
const infowindow = new google.maps.InfoWindow();
const infowindowContent = document.getElementById("infowindow-content");
infowindow.setContent(infowindowContent);
const marker = new google.maps.Marker({
map: map,
icon: markerIcon
});
marker.addListener("click", () => {
infowindow.open(map, marker);
});
autocomplete.addListener("place_changed", () => {
infowindow.close();
const place = autocomplete.getPlace();
if (!place.geometry || !place.geometry.location) {
return;
}
if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
} else {
map.setCenter(place.geometry.location);
map.setZoom(17);
}
marker.setPlace({
placeId: place.place_id,
location: place.geometry.location,
});
marker.setVisible(true);
infowindowContent.children.namedItem("place-name").textContent = place.name;
infowindowContent.children.namedItem("place-address").textContent = place.formatted_address;
infowindow.open(map, marker);
window.parent.postMessage([place.name, place.formatted_address, place.geometry.location.lat(), place.geometry.location.lng()], "*");
});
}
</script>
</head>
<body onload="initMap()">
<div id="input">
<input id="pac-input" class="controls" type="text" placeholder="add adress">
</div>
<div id="map"></div>
<div id="infowindow-content">
<span id="place-name" class="title"></span><br />
<span id="place-address"></span><br />
</div>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=MY_KEY&callback=initMap&libraries=places&v=weekly" async defer></script>
</body>
</html>
Related
I'm trying to locate the user when the website is fully loaded.
I'm using the newest MapBox API (JavaScript)
Is it possible to do that without requiring the user to click on the top right button on the map?
var map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/streets-v11',
center: [0,0],
zoom: 15 // starting zoom
});
// Add geolocate control to the map.
map.addControl(new mapboxgl.GeolocateControl({
positionOptions: {
enableHighAccuracy: true
},
trackUserLocation: true
}));
try with this example, it's work for me
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8' />
<title></title>
<meta name='viewport' content='initial-scale=1,maximum-scale=1,user-scalable=no' />
<script src='https://cdnjs.cloudflare.com/ajax/libs/mapbox-gl/0.53.1/mapbox-gl.js'></script>
<link href='https://cdnjs.cloudflare.com/ajax/libs/mapbox-gl/0.53.1/mapbox-gl.css' rel='stylesheet' />
<style>
body { margin:0; padding:0; }
#map { position:absolute; top:0; bottom:0; width:100%; }
</style>
<script >
var get_location = function() {
var geolocation = null;
var c_pos = null;
if (window.navigator && window.navigator.geolocation) {
geolocation = window.navigator.geolocation;
var positionOptions = {
enableHighAccuracy: true,
timeout: 10 * 1000, // 10 seconds
maximumAge: 30 * 1000 // 30 seconds
};
function success(position) {
console.log(position);
c_pos = position.coords;
mapboxgl.accessToken = 'token'; ///////////////// put your token here
if (!mapboxgl.supported()) {
alert('Your browser does not support Mapbox GL');
} else {
var map = new mapboxgl.Map({
container: 'map', // container id
style: 'mapbox://styles/mapbox/streets-v11',
center: [c_pos.longitude, c_pos.latitude],
zoom: 12 // starting zoom
});
}
}
function error(positionError) {
console.log(positionError.message);
}
if (geolocation) {
geolocation.getCurrentPosition(success, error, positionOptions);
}
} else {
alert("Getting Geolocation is prevented on your browser");
}
return c_pos;
}
</script>
</head>
<body>
<div id='map'></div>
<script>
var current_pos = get_location();
</script>
</body>
</html>
try with this
navigator.geolocation.getCurrentPosition(position => {
const userCoordinates = [position.coords.longitude, position.coords.latitude];
map.addSource("user-coordinates", {
type: "geojson",
data: {
type: "Feature",
geometry: {
type: "Point",
coordinates: userCoordinates
}
}
});
map.addLayer({
id: "user-coordinates",
source: "user-coordinates",
type: "circle"
});
map.flyTo({
center: userCoordinates,
zoom: 14
});
});
Yes, you have to use trigger() to activate the tracking in a programmed way.
// Initialize the geolocate control.
var geolocate = new mapboxgl.GeolocateControl({
positionOptions: {
enableHighAccuracy: true
},
trackUserLocation: true
});
// Add the control to the map.
map.addControl(geolocate);
map.on('load', function() {
geolocate.trigger(); //<- Automatically activates geolocation
});
see https://docs.mapbox.com/mapbox-gl-js/api/markers/#geolocatecontrol-instance-members
Nested AJAX call are used to get foursquare image URL.
First AJAX call is to derive venue ID from foursquare API and used in 2nd AJAX call to get image URL. Said image URL is used to render venue image in Google Map's Infowindow after each marker is clicked.
var map;
//Locations that automatically show on map
var locations =[
{
title: 'Empire State Building',
location: {
lat: 40.748541,
lng: -73.985758
} },
{
title: 'Radio City Music Hall',
location: {
lat: 40.759976,
lng: -73.979977
} },
{
title: 'Hotel Pennsylvania',
location: {
lat: 40.749772,
lng: -73.990624
}},
{
title: 'The Roosevelt Hotel',
location: {
lat: 40.754763,
lng: -73.977436
} },
{
title: 'Gershwin Theatre',
location: {
lat: 40.76234,
lng: -73.985235
}}];
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {
lat: 40.7413549,
lng: -73.99802439999996
},
zoom: 12
});
var infowindow = new google.maps.InfoWindow();
locations.forEach(function(location,i) {
this.position = locations[i].location;
var title = locations[i].title;
var marker = new google.maps.Marker({
position: position,
title: title,
map: map,
animation: google.maps.Animation.DROP,
id: i,
});
locations[i].marker = marker;
console.log('wunderbar', location);
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
var client_id = 'V443OTCAQPJLCRY4QWBFYN3ZK5FDKGJOYDHLMI3O342IRVNN';
var client_secret = 'AK1JHLEG2D2KW14WF5HYVFNTUYFTBXYS4LDUUNRAHPR5URLB';
var fourSquareUrl = 'https://api.foursquare.com/v2/venues/search?ll=' + self.position.lat + ',' + self.position.lng + '&query=' + marker.title+'&client_id=V443OTCAQPJLCRY4QWBFYN3ZK5FDKGJOYDHLMI3O342IRVNN&client_secret=AK1JHLEG2D2KW14WF5HYVFNTUYFTBXYS4LDUUNRAHPR5URLB&v=20170824';
$.getJSON(fourSquareUrl).done(function(data) {
console.log(data);
var response = data.response.venues["0"];
var venue_id = response.id;
this.address=response.location.formattedAddress;
var baseUrl = 'https://api.foursquare.com/v2/venues/';
var fsParam = '/?client_id=V443OTCAQPJLCRY4QWBFYN3ZK5FDKGJOYDHLMI3O342IRVNN&client_secret=AK1JHLEG2D2KW14WF5HYVFNTUYFTBXYS4LDUUNRAHPR5URLB&v=20131016';
var picUrl = baseUrl + venue_id + fsParam;
$.getJSON(picUrl).done(function(pic){
var venue_data = pic.response.venue;
self.img_url = venue_data.bestPhoto.prefix + '192x144' + venue_data.bestPhoto.suffix;
console.log(pic);
});
infowindow.setContent('<div><strong>' + locations[i].title +'<div>'+'<div>'+'<img src='+self.img_url+'>'+'</div>'+this.address+'</div>'+'</strong></div>');
//Alert User that there was a data request fail from third part API
}).fail(function() {
alert("Error");
});
infowindow.open(map, marker);
// sets animation to bounce 2 times when marker is clicked
marker.setAnimation(google.maps.Animation.BOUNCE);
setTimeout(function() {
marker.setAnimation(null);
}, 2130);
};
})(marker, i));
});
ko.applyBindings(new ViewModel());
}
var Loc = function(data) {
this.title = data.title;
this.location = data.location;
this.marker = data.marker;
console.log('wonderful', data);
};
var ViewModel = function() {
var self = this;
};
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="style.css">
<title> Local Map</title>
</head>
<body>
<div class="container">
<div class="forminline">
<ul>
<li></li>
</ul>
</div>
<div id="map">
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js">
</script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js'></script>
<script type="text/javascript" src='app.js'></script>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCE5O2RkGKfoHcOJt3JFg4ayHVizN7Dmgk&callback=initMap">
</script>
</body>
</html>
Accurately render each venue image in infowindow when each marker is clicked once.
When map is loaded, the first click on one marker did not render venue image in infowindow until it is clicked the second time. Chrome's developer tool console showed "net::ERR_FILE_NOT_FOUND".
When a second marker is clicked, image from first marker is rendered in infowindow until it is clicked the second time.
I appreciate any input on this as I am new to Javascript. Thanks in advance!
Infowindow setcontent was fired before nested AJAX call was completed. Therefore jQuery deferreds was used (with when & then statement) to ensure nested JSON is complete before setting content in infowindow.
Code as follow;
var map;
var locations =[
{
title: 'Empire State Building',
location: {
lat: 40.748541,
lng: -73.985758
} },
{
title: 'Radio City Music Hall',
location: {
lat: 40.759976,
lng: -73.979977
} },
{
title: 'Hotel Pennsylvania',
location: {
lat: 40.749772,
lng: -73.990624
}},
{
title: 'The Roosevelt Hotel',
location: {
lat: 40.754763,
lng: -73.977436
} },
{
title: 'Gershwin Theatre',
location: {
lat: 40.76234,
lng: -73.985235
}}];
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {
lat: 40.7413549,
lng: -73.99802439999996
},
zoom: 12
});
var infowindow = new google.maps.InfoWindow();
locations.forEach(function(location,i) {
this.position = locations[i].location;
var title = locations[i].title;
var marker = new google.maps.Marker({
position: position,
title: title,
map: map,
animation: google.maps.Animation.DROP,
id: i,
});
locations[i].marker = marker;
console.log('wunderbar', location);
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
var client_id = 'V443OTCAQPJLCRY4QWBFYN3ZK5FDKGJOYDHLMI3O342IRVNN';
var client_secret = 'AK1JHLEG2D2KW14WF5HYVFNTUYFTBXYS4LDUUNRAHPR5URLB';
var fourSquareUrl = 'https://api.foursquare.com/v2/venues/search?ll=' + self.position.lat + ',' + self.position.lng + '&query=' + marker.title+'&client_id=V443OTCAQPJLCRY4QWBFYN3ZK5FDKGJOYDHLMI3O342IRVNN&client_secret=AK1JHLEG2D2KW14WF5HYVFNTUYFTBXYS4LDUUNRAHPR5URLB&v=20170824';
$.when($.getJSON(fourSquareUrl).done(function(data) {
console.log(data);
var response = data.response.venues["0"];
var venue_id = response.id;
this.address=response.location.formattedAddress;
var baseUrl = 'https://api.foursquare.com/v2/venues/';
var fsParam = '/?client_id=V443OTCAQPJLCRY4QWBFYN3ZK5FDKGJOYDHLMI3O342IRVNN&client_secret=AK1JHLEG2D2KW14WF5HYVFNTUYFTBXYS4LDUUNRAHPR5URLB&v=20131016';
var picUrl = baseUrl + venue_id + fsParam;
$.getJSON(picUrl).done(function(pic){
var venue_data = pic.response.venue;
self.img_url = venue_data.bestPhoto.prefix + '192x144' + venue_data.bestPhoto.suffix;
console.log(pic);
}).then(function() {
infowindow.setContent('<div><strong>' + locations[i].title +'<div>'+'<div>'+'<img src='+self.img_url+'>'+'</div>'+this.address+'</div>'+'</strong></div>');
});
}).fail(function() {
alert("Error");
});
infowindow.open(map, marker);
marker.setAnimation(google.maps.Animation.BOUNCE);
setTimeout(function() {
marker.setAnimation(null);
}, 2130);
};
})(marker, i));
});
ko.applyBindings(new ViewModel());
}
var Loc = function(data) {
this.title = data.title;
this.location = data.location;
this.marker = data.marker;
console.log('wonderful', data);
};
var ViewModel = function() {
var self = this;
};
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="style.css">
<title> Local Map</title>
</head>
<body>
<div class="container">
<div class="forminline">
<ul>
<li></li>
</ul>
</div>
<div id="map">
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js">
</script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js'></script>
<script type="text/javascript" src='app.js'></script>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCE5O2RkGKfoHcOJt3JFg4ayHVizN7Dmgk&callback=initMap">
</script>
</body>
</html>
I am trying to recreate the following map, made using Google MyMaps, by using Google Maps API
Anyone know the best way to do this? Have the following code at the moment but doesn't look great
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Search for up to 200 places with Radar Search</title>
<style>
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
</style>
<script>
var map;
var infoWindow;
var service;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {
lat: 54.607868,
lng: -5.926437
},
zoom: 10,
styles: [{
stylers: [{
visibility: 'simplified'
}]
}, {
elementType: 'labels',
stylers: [{
visibility: 'off'
}]
}]
});
infoWindow = new google.maps.InfoWindow();
service = new google.maps.places.PlacesService(map);
// The idle event is a debounced event, so we can query & listen without
// throwing too many requests at the server.
map.addListener('idle', performSearch);
}
function performSearch() {
var request = {
bounds: map.getBounds(),
keyword: 'best view'
};
service.radarSearch(request, callback);
}
function callback(results, status) {
if (status !== google.maps.places.PlacesServiceStatus.OK) {
console.error(status);
return;
}
for (var i = 0, result; result = results[i]; i++) {
addMarker(result);
}
}
function addMarker(place) {
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location,
icon: {
url: 'https://developers.google.com/maps/documentation/javascript/images/circle.png',
anchor: new google.maps.Point(10, 10),
scaledSize: new google.maps.Size(10, 17)
}
});
google.maps.event.addListener(marker, 'click', function() {
service.getDetails(place, function(result, status) {
if (status !== google.maps.places.PlacesServiceStatus.OK) {
console.error(status);
return;
}
infoWindow.setContent(result.name);
infoWindow.open(map, marker);
});
});
}
</script>
</head>
<body>
<div id="map"></div>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCIcOfMnc85XkuJmotWkLL4mthAHqlUuWA&callback=initMap&libraries=places,visualization" async defer></script>
</body>
</html>
use a saved google my maps and share it from your google drive
How can i let the "address" locate a current location marker for the user on google map by clicking on the button rather than take the input value
http://jsfiddle.net/razanrab/WppF6/253/
<body>
<div id="panel">
<input id="city_country" type="textbox" value="Berlin, Germany">
<input type="button" value="Geocode" onclick="codeAddress()">
</div>
<div id="mapCanvas"></div>
<div id="infoPanel">
<b>Marker status:</b>
<div id="markerStatus"><i>Click and drag the marker.</i></div>
<b>Current position:</b>
<div id="info"></div>
<b>Closest matching address:</b>
<div id="address"></div>
</div>
</body>
//js
var geocoder;
var map;
var marker;
codeAddress = function () {
geocoder = new google.maps.Geocoder();
var address = document.getElementById('city_country').value;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map = new google.maps.Map(document.getElementById('mapCanvas'), {
zoom: 16,
streetViewControl: false,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR,
mapTypeIds:[google.maps.MapTypeId.HYBRID, google.maps.MapTypeId.ROADMAP]
},
center: results[0].geometry.location,
mapTypeId: google.maps.MapTypeId.
Location code is not working here.In fiddle it is working see link below
Fiddle Demonstration
Code below
// Note: This example requires that you consent to location sharing when
// prompted by your browser. If you see the error "The Geolocation service
// failed.", it means you probably did not give permission for the browser to
// locate you.
var map, infoWindow;
var geocoder;
function initMap() {
geocoder = new google.maps.Geocoder();
map = new google.maps.Map(document.getElementById('mapCanvas'), {
center: {
lat: -34.397,
lng: 150.644
},
zoom: 6
});
infoWindow = new google.maps.InfoWindow;
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
var marker = new google.maps.Marker({
position: pos,
map: map,
draggable: true,
title: 'Your position'
});
/*infoWindow.setPosition(pos);
infoWindow.setContent('Your position');
marker.addListener('click', function() {
infoWindow.open(map, marker);
});
infoWindow.open(map, marker);*/
map.setCenter(pos);
updateMarkerPosition(marker.getPosition());
geocodePosition(pos);
// Add dragging event listeners.
google.maps.event.addListener(marker, 'dragstart', function() {
updateMarkerAddress('Dragging...');
});
google.maps.event.addListener(marker, 'drag', function() {
updateMarkerStatus('Dragging...');
updateMarkerPosition(marker.getPosition());
});
google.maps.event.addListener(marker, 'dragend', function() {
updateMarkerStatus('Drag ended');
geocodePosition(marker.getPosition());
map.panTo(marker.getPosition());
});
google.maps.event.addListener(map, 'click', function(e) {
updateMarkerPosition(e.latLng);
geocodePosition(marker.getPosition());
marker.setPosition(e.latLng);
map.panTo(marker.getPosition());
});
}, function() {
handleLocationError(true, infoWindow, map.getCenter());
});
} else {
// Browser doesn't support Geolocation
handleLocationError(false, infoWindow, map.getCenter());
}
}
function geocodePosition(pos) {
geocoder.geocode({
latLng: pos
}, function(responses) {
if (responses && responses.length > 0) {
updateMarkerAddress(responses[0].formatted_address);
} else {
updateMarkerAddress('Cannot determine address at this location.');
}
});
}
function updateMarkerStatus(str) {
document.getElementById('markerStatus').innerHTML = str;
}
function updateMarkerPosition(latLng) {
document.getElementById('info').innerHTML = [
latLng.lat(),
latLng.lng()
].join(', ');
}
function updateMarkerAddress(str) {
document.getElementById('address').innerHTML = str;
}
function handleLocationError(browserHasGeolocation, infoWindow, pos) {
infoWindow.setPosition(pos);
infoWindow.setContent(browserHasGeolocation ?
'Error: The Geolocation service failed.' :
'Error: Your browser doesn\'t support geolocation.');
infoWindow.open(map);
}
#mapCanvas {
width: 300px;
height: 300px;
float: left;
}
#infoPanel {
float: left;
margin-left: 10px;
}
#infoPanel div {
margin-bottom: 5px;
}
<div id="panel">
<!--<input id="city_country" type="textbox" value="Berlin, Germany">-->
<input type="button" value="Locate Me" onclick="initMap()">
</div>
<div id="mapCanvas"></div>
<div id="infoPanel">
<b>Marker status:</b>
<div id="markerStatus"><i>Click and drag the marker.</i></div>
<b>Current position:</b>
<div id="info"></div>
<b>Closest matching address:</b>
<div id="address"></div>
</div>
<!-- Replace the value of the key parameter with your own API key. -->
<script async defer src="https://maps.googleapis.com/maps/api/js">
</script>
I have this code that allows the user to enter two cities, and shows the location of the given inputs. But what I want is to show as well the direction from the 1st city to the other. How to do that?
Here is my practice code:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0; padding: 0 }
#map_canvas { height: 100% }
</style>
<script type="text/javascript"
src="http://maps.googleapis.com/maps/api/js?key=AIzaSyBQ8OCC8En5vNHod25Ov3Qs5E1v7NPRSsg&sensor=true">
</script>
<script type="text/javascript">
var geocoder;
var map;
function initialize1() {
var mapOptions = {
center: new google.maps.LatLng(-34.397, 100.644),
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"),
mapOptions);
}
function initialize() {
// add mapOptions here to the values in the input boxes.
var mapOptions = {
center: new google.maps.LatLng(-34.397, 100.644),
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"),mapOptions);
geocoder = new google.maps.Geocoder();
addAddress(document.getElementById('from').value);
addAddress(document.getElementById('to').value);
}
function addAddress(place) {
var address = place;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
</script>
</head>
<body>
From: <input id="from" type="text" name="From"><br>
To: <input id="to" type="text" name="To"><br>
<button type="button" onclick="initialize()">View example (map-simple.html)</button>
<div id="map_canvas" style="width:100%; height:100%"></div>
</body>
</html>
thanks
Jason
Use the DirectionsService in the Google Maps API v3. Here is an example from the documentation:
https://google-developers.appspot.com/maps/documentation/javascript/examples/directions-simple
and with text directions:
https://google-developers.appspot.com/maps/documentation/javascript/examples/directions-panel
if you mean the "location" means the address you can use the direction renderer like below to get the direction.
First of all store the location address of the two markers into the two text boxes if you want to display the to and from address with id's #from and #destination then follow the below code
$("#find").click(function () {
starting = $("#from").val();
finishing = $("#destination").val();
$("#map").gmap3(
{
action: 'getRoute',
options: {
origin: starting,
destination: finishing,
travelMode: google.maps.DirectionsTravelMode.DRIVING
},
callback: function (results) {
if (!results) {
alert("returning")
return
};
$(this).gmap3(
{
action: 'addDirectionsRenderer',
options: {
preserveViewport: true,
draggable: false,
directions: results
}
}
);
}
})
})
Explanation : At first I created two markers of different locations and different data then after the dragend of any marker there will be infowindow that shows the address and two buttons start and finish. I think you have done upto this part .
So after this I used two text boxes which will be filled according to the start button or finish button clicked .
After this if the user clicks the find button this text boxes values are used to find the direction between the two markers
Note: "here you can any marker for from or to only difference you have to maintain is to change the button clicked that is start or finish ....."
"You can even directly give the address in the text boxes and find the directions between them"
Here for whole manipulation I used gmap3 here is the code below that might help you
<script type="text/javascript">
window.onload = clear;
function clear() {
$("#from").val(null)
$("#destination").val(null)
}
$(document).ready(function () {
var starting = "";
var finishing = "";
$("#find").click(function () {
starting = $("#from").val();
finishing = $("#destination").val();
$("#map").gmap3(
{
action: 'getRoute',
options: {
origin: starting,
destination: finishing,
travelMode: google.maps.DirectionsTravelMode.DRIVING
},
callback: function (results) {
if (!results) {
alert("returning")
return
};
$(this).gmap3(
{
action: 'addDirectionsRenderer',
options: {
preserveViewport: true,
draggable: false,
directions: results
}
}
);
}
})
})
$("#map").gmap3({
action: 'addMarkers',
markers: [ //markers array
{lat: 22.74, lng: 83.28, data: 'madhu' },
{ lat: 17.74, lng: 82.28, data: 'raghu' }
],
map: { // this is for map options not for any markers
center: [17.74, 83.28],
zoom: 5
},
marker: {
options: {
draggable: true
},
events: {// marker events
dragend: function (marker, event, data) {
var contentString = '<div id="main content">'
+ '<input type="button" id="start" value="start" />'
+ '<input type="button" id="finish" value="finish" />'
+ '</div>';
//get address on click event
$(this).gmap3({
action: 'getAddress',
latLng: marker.getPosition(),
callback: function (results) {
var map = $(this).gmap3('get'),
infowindow = $(this).gmap3({ action: 'get', name: 'infowindow' })
if (infowindow) {
content = results && results[1] ? results && results[1].formatted_address : 'no address';
infowindow.open(map, marker);
infowindow.setContent(content + contentString);
}
else {
content = results && results[1] ? results && results[1].formatted_address : 'no address';
$(this).gmap3({
action: 'addinfowindow',
anchor: marker,
options: { content: content + contentString },
events: {
domready: function () {
$("#start").click(function () {
alert("start clicked " + content);
$("#from").val(content);
starting = content;
check();
})
$("#finish").click(function () {
alert("finish clicked " + content);
$("#destination").val(content);
finishing = content;
})
}
}
});
}
}
});
},
}
},
});
});
</script>
here is the html part for the above
<div id="headinput">
<input type="text" value="enter from" id="from" />
<input type="text" value="enter destination" id="destination" />
<input type="button" value="find" id="find" />
</div>
<br />
<div id ="map"style="width: 100%; top: auto; left: auto; position: relative; height: 600px; float:left" ></div>
This is perfectly worked one I checked it in firefox browser........:D