In the following code I've added a custom control on a map using Google Maps API V3.
<html>
<head>
<title>Simple Map</title>
<meta name="viewport" content="initial-scale=1.0">
<meta charset="utf-8">
<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>
<script>
var map;
function initMap() {
var myOptions = {
zoom: 8,
center: {lat: -34.397, lng: 150.644},
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map"), myOptions);
//### Add a button on Google Maps ...
var controlMarkerUI = document.createElement('DIV');
controlMarkerUI.style.cursor = 'pointer';
controlMarkerUI.style.backgroundColor = 'blue';
controlMarkerUI.style.height = '28px';
controlMarkerUI.style.width = '25px';
controlMarkerUI.style.top = '11px';
controlMarkerUI.style.left = '120px';
controlMarkerUI.title = 'Click to get the coordinates';
map.controls[google.maps.ControlPosition.LEFT_TOP].push(controlMarkerUI);
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=<PUT_YOUR_KEY_HERE>&callback=initMap"
async defer></script>
</body>
</html>
Now I'd like to associate a function at the custom control tha simply return the click coordinates when a user click on the map.
I can do it (without associate the function to the customcontrol ... ), in this manner
google.maps.event.addListener(map, 'click', function (e) {
alert("Latitude: " + e.latLng.lat() + "\r\nLongitude: " + e.latLng.lng());
});
but I'd like to activate / deactivate this function clicking on my custom control.
Suggestions / examples?
<html>
<head>
<title>Simple Map</title>
<meta name="viewport" content="initial-scale=1.0">
<meta charset="utf-8">
<style>
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 70%;
}
/* Optional: Makes the sample page fill the window. */
html, body {
height: 100%;
margin: 0;
padding: 0;
}
</style>
</head>
<body>
<div id="map"></div>
<button id="start">Start</button>
<button id="clearClick">Clear</button>
<script>
var map;
var listener1;
function initMap() {
var myOptions = {
zoom: 8,
center: {lat: -34.397, lng: 150.644},
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map"), myOptions);
//### Add a button on Google Maps ...
var controlMarkerUI = document.createElement('DIV');
controlMarkerUI.style.cursor = 'pointer';
controlMarkerUI.style.backgroundColor = 'blue';
controlMarkerUI.style.height = '28px';
controlMarkerUI.style.width = '25px';
controlMarkerUI.style.top = '11px';
controlMarkerUI.style.left = '120px';
controlMarkerUI.title = 'Click to get the coordinates';
listener1= google.maps.event.addListener(map, 'click', function
(e) {
alert("Latitude: " + e.latLng.lat() + "\r\nLongitude: " + e.latLng.lng());
});
document.getElementById("clearClick").onclick = function(){
google.maps.event.removeListener(listener1);
}
document.getElementById("start").onclick = function(){
listener1= google.maps.event.addListener(map, 'click', function
(e) {
alert("Latitude: " + e.latLng.lat() + "\r\nLongitude: " + e.latLng.lng());
});
}
map.controls[google.maps.ControlPosition.LEFT_TOP].push(controlMarkerUI);
}
</script>
<script>
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=&callback=initMap"
async defer></script>
</body>
</html>
For further ref below link
https://developers.google.com/maps/documentation/javascript/events
Merging #Murali answer and this answer https://gis.stackexchange.com/questions/244132/how-to-associate-function-to-custom-controls-in-google-maps-api/244141#244141, I solved in this way ....
<html>
<head>
<title>Simple Map</title>
<meta name="viewport" content="initial-scale=1.0">
<meta charset="utf-8">
<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>
<script>
var map;
var listenerHandle;
//Enable-Disable the functionality
function show_XY(e){
listenerHandle = google.maps.event.addListener(map, 'click', alert_XY);
}
function alert_XY(e){
alert("Latitude: " + e.latLng.lat() + "\r\nLongitude: " + e.latLng.lng());
}
function removeListener(e){
google.maps.event.removeListener(listenerHandle);
}
function initMap() {
var myOptions = {
zoom: 8,
center: {lat: -34.397, lng: 150.644},
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map"), myOptions);
//### Add a button on Google Maps ...
var controlEditUI = document.createElement('DIV');
controlEditUI.id = "controlEditUI";
controlEditUI.style.cursor = 'pointer';
controlMarkerUI.style.backgroundColor = 'blue';
controlEditUI.style.height = '28px';
controlEditUI.style.width = '25px';
controlEditUI.style.top = '11px';
controlEditUI.style.left = '120px';
controlEditUI.title = 'Click to get the coordinates';
map.controls[google.maps.ControlPosition.LEFT_TOP].push(controlEditUI);
controlEditUI.addEventListener('click', show_XY);
//### Add a button on Google Maps ...
var controlTrashUI = document.createElement('DIV');
controlTrashUI.id = 'controlTrashUI';
controlTrashUI.style.cursor = 'pointer';
controlMarkerUI.style.backgroundColor = 'black';
controlTrashUI.style.height = '28px';
controlTrashUI.style.width = '25px';
controlTrashUI.style.top = '11px';
controlTrashUI.style.left = '150px';
controlTrashUI.title = 'Click to set the map to Home';
map.controls[google.maps.ControlPosition.LEFT_TOP].push(controlTrashUI);
controlTrashUI.addEventListener('click', removeListener);
};
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=<PUT_YOUR_KEY_HERE>&callback=initMap"
async defer></script>
</body>
</html>
Related
I am making a webpage with Google Maps API but I am getting "google not defined error"
How can I get rid of this?
How can I import Google or do something to make this piece of code work?
I want a program in which user will enter location and it shows marker there. but it is not working properly.
Here is my code:
<!DOCTYPE html>
<html>
<head>
<title>Simple Map</title>
<meta name="viewport" content="initial-scale=1.0">
<meta charset="utf-8">
<style>
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#map {
height: 100%;
}
</style>
</head>
<body>
<h1>Perform Google Maps Search</h1>
<h3> Please enter the place you want to search</h3>
<input type="text" id="mapsearch" size="50"> <br>
<br>
<div id="map"></div>
<script>
var map;
function initMap() {
var myOptions = {
zoom:14,
navigationControl: true,
scaleControl: true,
panControl: true,
center: new google.maps.LatLng(43.6532,-79.3832),
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById('map'),myOptions);
var marker = new google.maps.Marker({
position: new google.maps.LatLng(43.6532,-79.3832),
title:"Toronto"
});
marker.setMap(map);
}
var searchBox = new google.maps.places.SearchBox(document.getElementById('mapsearch'));
map.controls[google.maps.ControlPosition.TOP_CENTER].push(document.getElementById('mapsearch'));
google.maps.event.addListener(searchBox, 'places_changed', function() {
searchBox.set('map', null);
var places = searchBox.getPlaces();
var bounds = new google.maps.LatLngBounds();
var i, place;
for (i = 0; place = places[i]; i++) {
(function(place) {
var marker = new google.maps.Marker({
position: place.geometry.location
});
marker.bindTo('map', searchBox, 'map');
google.maps.event.addListener(marker, 'map_changed', function() {
if (!this.getMap()) {
this.unbindAll();
}
});
bounds.extend(place.geometry.location);
}(place));
}
map.fitBounds(bounds);
searchBox.set('map', map);
map.setZoom(Math.min(map.getZoom(),12));
});
google.maps.event.addDomListener(window, 'load', init);
</script>
<script src="https://maps.googleapis.com/maps/api/js?key="Your_API_Key"&callback=initMap"
async defer></script>
</body>
</html>
initMap function should be closed at last you are closing it before
var searchBox = new google.maps.places.SearchBox(document.getElementById('mapsearch'));
So you are getting google undefined error.
Also you have add parameter &libraries=places to google map script src
working example
https://plnkr.co/edit/ngtGvuhDDZAnovwPnPXh?p=preview
// Code goes here
var map;
function initMap() {
var myOptions = {
zoom:14,
navigationControl: true,
scaleControl: true,
panControl: true,
center: new google.maps.LatLng(43.6532,-79.3832),
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById('map'),myOptions);
var marker = new google.maps.Marker({
position: new google.maps.LatLng(43.6532,-79.3832),
title:"Toronto"
});
marker.setMap(map);
var searchBox = new google.maps.places.SearchBox(document.getElementById('mapsearch'));
map.controls[google.maps.ControlPosition.TOP_CENTER].push(document.getElementById('mapsearch'));
google.maps.event.addListener(searchBox, 'places_changed', function() {
searchBox.set('map', null);
var places = searchBox.getPlaces();
var bounds = new google.maps.LatLngBounds();
var i, place;
for (i = 0; place = places[i]; i++) {
(function(place) {
var marker = new google.maps.Marker({
position: place.geometry.location
});
marker.bindTo('map', searchBox, 'map');
google.maps.event.addListener(marker, 'map_changed', function() {
if (!this.getMap()) {
this.unbindAll();
}
});
bounds.extend(place.geometry.location);
}(place));
}
map.fitBounds(bounds);
searchBox.set('map', map);
map.setZoom(Math.min(map.getZoom(),12));
});
}
<!DOCTYPE html>
<html>
<head>
<title>Simple Map</title>
<meta name="viewport" content="initial-scale=1.0">
<meta charset="utf-8">
<style>
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#map {
height: 100%;
}
</style>
</head>
<body>
<h1>Perform Google Maps Search</h1>
<h3> Please enter the place you want to search</h3>
<input type="text" id="mapsearch" size="50"> <br>
<br>
<div id="map"></div>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAtaKPvRV8-ciYtnnzG3QI3CO7m4HJyhaI&libraries=places&callback=initMap"
async defer></script>
</body>
</html>
Most likely your google APIs have not loaded, when your script needs them - hence the "google not defined error". Move this before your script and drop the async defer - or do your script inside a "$( document ).ready"
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAtaKPvRV8-ciYtnnzG3QI3CO7m4HJyhaI&callback=initMap"
async defer></script>
I'm building JS app.Tasks are:
1.Locate me and find nearest ATMs of specified bank
2.Then sort what she found in list.Sort by distance from me.
3.On the end are some design like a image on marker of store etc..
Well I did to locate me and to show me locations of ATMs
But I can't figure out to create list and sort that ATMs by distance from me
Does someone can help me
My code is
<!DOCTYPE html>
<html>
<head>
<title>Place searches</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<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>
<script>
// This example requires the Places library. Include the libraries=places
// parameter when you first load the API. For example:
// <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places">
var map;
var infowindow;
function initMap() {
var pyrmont = {lat: -33.867, lng: 151.195};
map = new google.maps.Map(document.getElementById('map'), {
center: pyrmont,
zoom: 15
});
infowindow = new google.maps.InfoWindow();
var service = new google.maps.places.PlacesService(map);
service.nearbySearch({
location: pyrmont,
radius: 500,
type: ['store']
}, callback);
}
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
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(place.name);
infowindow.open(map, this);
});
}
</script>
</head>
<body>
<div id="map"></div>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCW8gRR1ITJDx4F-rVpkBSetftu32XO2P0&libraries=places&callback=initMap" async defer></script>
Thanks
I have a code but the problem is the watchposition() is relaoding the full map.What I want is a code to refresh only marker's position. Here's what I've done:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Geo Location</title>
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0; padding: 0 }
#map-canvas{ height: 100% }
</style>
<script type="text/javascript">
function onSuccess(position) {
var lat=position.coords.latitude;
var lang=position.coords.longitude;
var myLatlng = new google.maps.LatLng(lat,lang);
var mapOptions = {zoom: 4,center: myLatlng};
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
var marker = new google.maps.Marker({position: myLatlng,map: map});
}
function onError(error) {
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}
var watchID=navigator.geolocation.watchPosition(onSuccess,onError{timeout:30000 });
</script>
</head>
<body>
<div id="map-canvas"></div>
</body>
</html>
use setPosition()
sth like this?
https://plnkr.co/edit/UgCEnQ?p=preview
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
</head>
<body>
<style>
#map {
width: 100%;
height: 300px;
}
</style>
<div id="map"></div>
<script>
var marker, map;
function initMap() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var lat = position.coords.latitude;
var lng = position.coords.longitude;
var myLatLng = new google.maps.LatLng(lat, lng);
map = new google.maps.Map(document.getElementById('map'), {
center: myLatLng,
zoom: 18
});
if (marker != undefined) {
marker.setPosition(myLatLng);
} else {
marker = new google.maps.Marker({
position: myLatLng,
map: map
});
}
});
}
}
</script>
<script src="https://maps.google.com/maps/api/js?callback=initMap" async defer></script>
</body>
</html>
I have this code which shows a marker from my current location and sets the coordinates into the page title, buy now I want to add a search box for adresses but I need that the text of the search box changes to the corresponding coordinates when the markes is draged. and i have no idea hot to do that
here is my code
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<style>
#map_canvas{
height:800px;
width:800px;
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?sensor=true">
</script>
<script>
navigator.geolocation.getCurrentPosition(initialize);
var marker, map;
function initialize(position ) {
var coords = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
var mapOptions = {
zoom: 14,
center: coords,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById('map_canvas'),
mapOptions);
window.document.title= new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
var mark = new google.maps.Marker({
position: coords ,
map: map,
draggable:true
});
google.maps.event.addListener(mark, 'dragend', function(evt){
window.document.title = evt.latLng.lat() + ',' + evt.latLng.lng() ;
});
}
</script>
</head>
<body onload="initialize()">
<div id="map_canvas"></div>
</body>
</html>
Test this, and tell me what you think of it
I used the document.getElementById() to select the search_box, and changed its innerHTML.
I slightly modified your event listener
google.maps.event.addListener(mark, 'dragend', function(evt){
var coordinates = {lat: evt.latLng.lat(), lng: evt.latLng.lng()};
window.document.title = coordinates.lat + ',' + coordinates.lng ;
document.getElementById('search_box').innerHTML = coordinates.lat + ',' + coordinates.lng ;
});
and I added a div with an id of search_box in your HTML.
Dear all i am a newbie to Google Maps API. I have a parsed a KML layer in Google Maps API using GeoXML3. Now how do i fetch placement marker value(Name of the place) of KML in Google Maps API onclick. Like when a kml layer gets loaded on google maps and i am clicking on any marker i should be able to fetch the placement value of the marker in an alert box. Please find the code that helps me parse a kml on google maps api. Please guide.
<!DOCTYPE html>
<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>KML Layer</title>
<link href="/maps/documentation/javascript/examples/default.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript" src="http://geoxml3.googlecode.com/svn/branches/polys/geoxml3.js"></script>
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0; padding: 0 }
#map_canvas { height: 100% }
</style>
<script type="text/javascript">
function initialize()
{
var chicago = new google.maps.LatLng(75.602836700999987,32.261890444473394);
var myOptions = {
zoom: 2,
center: chicago,
mapTypeId: google.maps.MapTypeId.ROADMAP }
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
//var transitLayer = new google.maps.TransitLayer();
//transitLayer.setMap(map);
var geoXml = new geoXML3.parser({map: map, singleInfoWindow: true});
geoXml.parse('kmload.kml');
var geoXml1 = new geoXML3.parser({map: map, singleInfoWindow: true});
geoXml1.parse('lines.kml');
}
</script>
</head>
<body onload="initialize()">
<div id="map_canvas"></div>
</body>
</html>
Is this what you are looking for? I have added the alert in the onclick function which displays me the name of the placemark in the alert box. Please check and let me know if you find any issues.
<!DOCTYPE>
<html>
<head>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false&libraries=places"></script>
<script type="text/javascript" src="http://geoxml3.googlecode.com/svn/branches/polys/geoxml3.js"></script>
<script type="text/javascript" src="http://geoxml3.googlecode.com/svn/trunk/ProjectedOverlay.js"></script>
<title>KML Placement Value Test</title>
<style>
html, body, #map_canvas {
height: 100%;
margin: 0;
padding: 0;
}
#panel {
top: 5px;
left: 85%;
margin-left: -180px;
z-index: 5;
background-color: #fff;
padding: 5px;
border: 1px solid #999;
}
.infowindow * {font-size: 90%; margin: 0}
</style>
<script type="text/javascript" >
geocoder = new google.maps.Geocoder();
var geoXml = null;
var geoXmlDoc = null;
var map = null;
var myLatLng = null;
var myGeoXml3Zoom = true;
var marker = [];
var polyline;
function initialize()
{
myLatLng = new google.maps.LatLng(37.422104808,-122.0838851);
var test;
var lat = 37.422104808;
var lng = -122.0838851;
var zoom = 18;
var maptype = google.maps.MapTypeId.ROADMAP;
if (!isNaN(lat) && !isNaN(lng))
{
myLatLng = new google.maps.LatLng(lat, lng);
}
var myOptions = {zoom: zoom,center: myLatLng,mapTypeId: maptype};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
infowindow = new google.maps.InfoWindow({});
geoXml = new geoXML3.parser({map: map,infoWindow: infowindow,singleInfoWindow: true,zoom: myGeoXml3Zoom, markerOptions: {optimized: false},createMarker: createMarker});
geoXml.parse('test.kml');
};
var createMarker = function (placemark, doc) {
var markerOptions = geoXML3.combineOptions(geoXml.options.markerOptions, {
map: geoXml.options.map,
position: new google.maps.LatLng(placemark.Point.coordinates[0].lat, placemark.Point.coordinates[0].lng),
title: placemark.name,
zIndex: Math.round(placemark.Point.coordinates[0].lat * -100000)<<5,
icon: placemark.style.icon,
shadow: placemark.style.shadow
});
// Create the marker on the map
var marker = new google.maps.Marker(markerOptions);
if (!!doc) {
doc.markers.push(marker);
}
// Set up and create the infowindow if it is not suppressed
if (!geoXml.options.suppressInfoWindows) {
var infoWindowOptions = geoXML3.combineOptions(geoXml.options.infoWindowOptions, {
content: '<div class="geoxml3_infowindow"><h3>' + placemark.name +
'</h3><div>' + placemark.description + '</div></div>',
pixelOffset: new google.maps.Size(0, 2)
});
if (geoXml.options.infoWindow) {
marker.infoWindow = geoXml.options.infoWindow;
} else {
marker.infoWindow = new google.maps.InfoWindow(infoWindowOptions);
}
marker.infoWindowOptions = infoWindowOptions;
// Infowindow-opening event handler
google.maps.event.addListener(marker, 'click', function()
{
alert(placemark.name);
this.infoWindow.close();
marker.infoWindow.setOptions(this.infoWindowOptions);
this.infoWindow.open(this.map, this);
});
}
placemark.marker = marker;
return marker;
};
</script>
</head>
<body onload="initialize()">
<div id="map_canvas" style="float: left; width: 70%; height: 100%;"></div>
</body>
</html>
If you use the "afterParse" function to add click listeners to the markers, you can access the data (if you use function closure), example accessing the name:
// assign "useTheData" as the after parse function
var geoXml = new geoXML3.parser({map: map, singleInfoWindow: true, afterParse: useTheData});
geoXml.parse('kmload.kml');
// function to retain closure on the placemark and associated text
function bindPlacemark(placemark, text) {
google.maps.event.addListener(placemark,"click", function() {alert(text)});
}
// "afterParse" function, adds click listener to each placemark to "alert" the name
function useTheData(doc) {
for (var i = 0; i < doc[0].placemarks.length; i++) {
var placemark = doc[0].placemarks[i].polygon || doc[0].placemarks[i].marker || doc[0].placemarks[i].polyline;
bindPlacemark(placemark, doc[0].placemarks[i].name);
}
};
working example
hope it can help ;)
/**
* map
*/
var myLatlng = new google.maps.LatLng(39.980278, 4.049835);
var myOptions = {
zoom: 10,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
scrollwheel: false
}
var map = new google.maps.Map(document.getElementById('mapa'), myOptions);
var infoWindow = new google.maps.InfoWindow();
var markerBounds = new google.maps.LatLngBounds();
var markerArray = [];
function makeMarker(options){
var pushPin = new google.maps.Marker({map:map});
pushPin.setOptions(options);
google.maps.event.addListener(pushPin, 'click', function(){
infoWindow.setOptions(options);
infoWindow.open(map, pushPin);
});
markerArray.push(pushPin);
return pushPin;
}
google.maps.event.addListener(map, 'click', function(){
infoWindow.close();
});
function openMarker(i){
google.maps.event.trigger(markerArray[i],'click');
};
/**
*markers
*/
makeMarker({
position: new google.maps.LatLng(39.943962, 3.891220),
title: 'Title',
content: '<div><h1>Lorem ipsum</h1>Lorem ipsum dolor sit amet<div>'
});
openMarker(0);