var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {
lat: 30.3434,
lng: 30.234
},
zoom: 8
});
}
/* 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;
}
<div id="map"></div>
<script src="https://maps.googleapis.com/maps/api/js?key=&callback=initMap" async defer></script>
how to input coordinates to google api java script automatically ?!
here is the code
<!DOCTYPE html>
<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() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat:30.3434, lng:30.234},
zoom: 8
});
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=&callback=initMap"
async defer></script>
</body>
</html>
i want to the "center" to take the coordinates from a txt file at my pc at as a test
Assuming your file is location.txt and the content is something like:
lat;long, e.g. 30.3434;30.234
You can do what you want using jQuery:
function initMap() {
var myLat, myLng, myMap;
$.ajax({
url : "location.txt",
dataType: "text",
success : function (data) {
var location = data.split(";");
myLat=location[0];
myLng=location[1]
},
error: function(data) {
console.log("unable to retrieve data from location.txt")
},
complete: function(data) {
//Called after success and error callbacks are executed.
myMap = new google.maps.Map(document.getElementById('map'), {
center: {lat:myLat, lng:myLng},
zoom: 8
});
}
});
}
Related
I have a map done on mapbox gl js.
I'm trying to get a placename / address by reverse geocoding longitude and latitude coordinates.
I can manage to get normal forward geocoding to work but querying the following (for example):
geocoder.query('New York')
But i cant quite figure out how to do this in reverse with coordinates. I've tried the following to no avail:
// geocoder.query(126.981,37.539)
// geocoder.query("126.981,37.539")
// geocoder.query(37.539,126.981)
// geocoder.query("37.539,126.981")
I couldnt find anything in the documents to point me in the right direction as well. Thus any help is greatly appreciated.
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8' />
<title>Set a point after Geocoder result</title>
<meta name='viewport' content='initial-scale=1,maximum-scale=1,user-scalable=no' />
<script src='https://api.tiles.mapbox.com/mapbox-gl-js/v0.49.0/mapbox-gl.js'></script>
<link href='https://api.tiles.mapbox.com/mapbox-gl-js/v0.49.0/mapbox-gl.css' rel='stylesheet' />
<style>
body { margin:0; padding:0; }
#map { position:absolute; top:0; bottom:0; width:100%; }
.built_address {
position: fixed;
top: 0;
left: 0;
background-color: white;
padding: 10px;
font-size: 12px;
font-family: Arial;
}
</style>
</head>
<body>
<script src='https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-geocoder/v2.3.0/mapbox-gl-geocoder.min.js'></script>
<link rel='stylesheet' href='https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-geocoder/v2.3.0/mapbox-gl-geocoder.css' type='text/css' />
<style>
#geocoder-container > div {
min-width:50%;
margin-left:25%;
}
</style>
<div id='map'></div>
<div class="built_address">LOREM IPSUM</div>
<script>
var built_address = '';
var user_coordinates;
var geocode_results;
mapboxgl.accessToken = 'pk.eyJ1IjoiZmFyaXNrYXNzaW0iLCJhIjoiSk1MaUthdyJ9.vkxtdDbYdLi524WwlKORBw';
var map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/fariskassim/cjmszx78b266o2rlar02ytynj',
center: [127.017768, 37.59837],
zoom: 12
});
var geocoder = new MapboxGeocoder({
accessToken: mapboxgl.accessToken
});
map.addControl(geocoder);
// After the map style has loaded on the page, add a source layer and default
// styling for a single point.
map.on('load', function() {
map.addSource('single-point', {
"type": "geojson",
"data": {
"type": "FeatureCollection",
"features": []
}
});
map.addLayer({
"id": "point",
"source": "single-point",
"type": "circle",
"paint": {
"circle-radius": 10,
"circle-color": "#007cbf"
}
});
getUserLocation();
});
function getUserLocation() {
// request to allow user position
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
function showPosition(position) {
// get user current coordinates and center map on coordiates
console.log('L2', position)
//console.log(position.coords.latitude, position.coords.latitude)
user_coordinates = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
// draw user location on mao
map.getSource('single-point').setData({type: "Point", coordinates: [user_coordinates.lng,user_coordinates.lat]});
// geocoder.query(user_coordinates.lat, user_coordinates.lng)
// Listen for the `result` event from the MapboxGeocoder that is triggered when a user
// makes a selection and add a symbol that matches the result.
geocoder.on('result', function(ev) {
map.getSource('single-point').setData(ev.result.geometry);
console.log('ev',ev)
built_address = ev.result.place_name
});
}
} else {
// if device doesnt support location
console.log('device doesnt support location')
}
}; /* END getUserLocation(); */
</script>
</body>
</html>
Try geocoder.mapboxClient.geocodeReverse:
geocoder.mapboxClient
.geocodeReverse({
latitude: user_coordinates.lat,
longitude: user_coordinates.lng
}, function(err, res) {
console.log(err, res)
});
Update
mapbox-gl-geocoder v5.0.0
You have to create a geocoder with reverse geocoding enabled :
let geocoder = new MapboxGeocoder({
accessToken:mapboxgl.accessToken,
mapboxgl:mapboxgl,
reverseGeocode:true
})
Then you will be able to do :
geocoder.query("126.981,37.539")
...
Be aware that the default coordinates format is lat,lng but you can invert it with the options.flipCoordinates
This question already has answers here:
Google Maps JS API v3 - Simple Multiple Marker Example
(15 answers)
Closed 4 years ago.
I am trying to use Google maps API for a website and I can't seem to get multiple locations to populate like Google has it in their example.
Could anyone please let me know what I need to add to get 11 markers to show up that will give a description of what I want.
I can see that Google has multiple locations giving a quick description of what they are.
PS: I already have a key I just need to know how to include "X" number of markers with a description attached.
Attached is the link to googles example:
Google Maps API
Here is the code:
<!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=YOUR_API_KEY&libraries=places&callback=initMap" async defer></script>
</body>
</html>
You need to try this:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Simple markers</title>
<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>
function initMap() {
var myLatLng = {
lat: -25.363,
lng: 131.044
};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: myLatLng
});
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
title: 'Hello World!'
});
}
</script>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
</script>
This is the code I have, based on the example at https://developers.google.com/maps/documentation/javascript/examples/event-simple , but instead of zooming in when clicked on a marker, I want to show a messagebox (alert()):
<!DOCTYPE html>
<html>
<head>
<title>Simple click event - modified</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<style>
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#map {
height: 100%;
}
</style>
</head>
<body>
<div id="map"></div>
<script>
function initMap() {
var myLatlng = {lat: -25.363, lng: 131.044};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: myLatlng
});
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: 'Click to show alert'
});
marker.addListener('click', alert('Hello World!'));
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&signed_in=true&callback=initMap" async defer>
</script>
</body>
</html>
Of course, instead of YOUR_API_KEY , I filled in my own API key from Google Maps API v3.
Whenever I load this page, the alert shows as soon as the page is loaded, and clicking on the marker has no effect at all.
The problem is in the addlistener, the command for the messagebox has to be in between a function() { ... }:
marker.addListener( 'click', function() { alert('Hello World!'); } );
Will solve the problem!
I've got a map in a hidden div that gets revealed by a button press. I was initially having issues but they were fixed by triggering a resize event. My issue now is that the map isn't centered on the position that I initialise the map with.
I want to add a map.setCenter(?) call in to the resize or bounds changed event listener but they never seem to be called. I've put alerts in each one to test but nothing happens.
EDIT: Example as requested...
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Simple markers</title>
<style>
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#theButton {
position: absolute;
top: 0;
left: 400px;
padding: 10px;
background-color: orange;
z-index: 100;
}
#map {
height: 100%;
}
</style>
</head>
<body>
<div id="theButton" onclick="resizeMap();">Click Me</div>
<div id="map"></div>
<script>
function initMap() {
var myLatLng = {lat: 51.320151, lng: -0.555658};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: myLatLng
});
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
title: 'Test Location!'
});
var getCen = map.getCenter();
var currentMapCenter = null;
google.maps.event.addListener(map, 'resize', function () {
currentMapCenter = map.getCenter();
alert("Resizing");
});
google.maps.event.addListener(map, 'bounds_changed', function () {
if (currentMapCenter) {
// react here
map.setCenter(currentMapCenter);
alert("Centering");
}
currentMapCenter = null;
});
}
function resizeMap() {
alert("Clicked");
google.maps.event.trigger(map, 'resize');
};
</script>
<script async defer src="https://maps.googleapis.com/maps/api/js?signed_in=true&callback=initMap"></script>
</body>
</html>
I have tested more deeply your code there is a problem with the scope of the var map
change declaration in this way (in window scope outside the function initMap local scope)
<script>
var map;
function initMap() {
var myLatLng = {lat: 51.320151, lng: -0.555658};
map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: myLatLng
});
........
......
Otherwise map is not correctly referenced in ths other function eg:
function resizeMap() {
google.maps.event.trigger(map, 'resize');
In this function if you don't change the var declaration map is not referenced and the nothing can be triggered
Looked over the example can NOT figure out how to set basemap MANUALLY. I don't want a dijit widget, or any other libraries or anything like that. Just want to manually set a basemap to any of the already available types like Topographic, Satellites, Streets, etc.
Following this API reference:
Object: esri/basemaps
The part I can't figure out is marked with question marks. If some could help me out, would really appreciate it.
require([
"esri/basemaps",
"esri/map",
"dojo/domReady!"
], function (esriBasemaps, Map) {
/* ------------------------------------- */
/* Basemap add one of the existing maps. */
/* ------------------------------------- */
esriBasemaps.myBasemap = {
baseMapLayers ???
};
var map = new Map("map", {
basemap: "myBasemap",
center: [-118, 34.5],
zoom: 8
});
});
The code in the esri/basemaps documentation works fine, combined with the create a map sample.
Here's the part you wondered about:
esriBasemaps.myBasemap = {
baseMapLayers: [
{
url: "http://services.arcgisonline.com/ArcGIS/rest/services/Specialty/DeLorme_World_Base_Map/MapServer"
}
],
title: "My Basemap"
};
Here's a full example. Copy and paste the following into the ArcGIS API for JavaScript Sandbox to see how it works.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1,user-scalable=no"/>
<title>Simple Map</title>
<link rel="stylesheet" href="http://js.arcgis.com/3.13/esri/css/esri.css">
<style>
html, body, #map {
height: 100%;
width: 100%;
margin: 0;
padding: 0;
}
body {
background-color: #FFF;
overflow: hidden;
font-family: "Trebuchet MS";
}
</style>
<script src="http://js.arcgis.com/3.13/"></script>
<script>
var map;
require(["esri/basemaps", "esri/map", "dojo/domReady!"], function(esriBasemaps, Map) {
esriBasemaps.myBasemap = {
baseMapLayers: [
{
url: "http://services.arcgisonline.com/ArcGIS/rest/services/Specialty/DeLorme_World_Base_Map/MapServer"
}
],
title: "My Basemap"
};
map = new Map("map", {
basemap: "myBasemap",
center: [-122.45, 37.75], // longitude, latitude
zoom: 13
});
});
</script>
</head>
<body>
<div id="map"></div>
</body>
</html>