Retrieve marker position to fields to submit - javascript

I have this code from the Google API docs. It does exactly what I want except i need to be able to get to get latitude and longitude of the marker once its been placed.
In my site , i have enabled the option to be able to select a location on the map, but i need to somehow get the latitude and longitude information from the marker that the customer has set, specifically in hidden fields so that i could store them when data is posted $_POST.
The code I have now is:
<!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=jsdlkajslkdjaslkdja&sensor=false&language=ar&region=SAU">
</script>
<script type="text/javascript">
var map;
var markersArray = [];
function initialize() {
var haightAshbury = new google.maps.LatLng(26.1631, 50.2044188);
var mapOptions = {
zoom: 7,
center: haightAshbury,
mapTypeId: google.maps.MapTypeId.TERRAIN
};
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
google.maps.event.addListener(map, 'click', function(event) {
addMarker(event.latLng);
});
}
function addMarker(location) {
marker = new google.maps.Marker({
position: location,
map: map
});
markersArray.push(marker);
}
// Removes the overlays from the map, but keeps them in the array
function clearOverlays() {
if (markersArray) {
for (i in markersArray) {
markersArray[i].setMap(null);
}
}
}
// Shows any overlays currently in the array
function showOverlays() {
if (markersArray) {
for (i in markersArray) {
markersArray[i].setMap(map);
}
}
}
// Deletes all markers in the array by removing references to them
function deleteOverlays() {
if (markersArray) {
for (i in markersArray) {
markersArray[i].setMap(null);
}
markersArray.length = 0;
}
}
</script>
</head>
<body onload="initialize()">
<div id="map_canvas" style="width:100%; height:100%"></div>
</body>
</html>
I mainly need help on the JS side of this.

There is a markersArray-variable which contains all markers.
Loop over the array, you will get the lat/lng for each item by using
item.getPosition().lat() and item.getPosition().lng()
<edit>
Limiting to 1 marker is easy.
Change this line:
google.maps.event.addListener(map, 'click', function(event) {
into this:
google.maps.event.addListenerOnce(map, 'click', function(event) {
</edit>

Related

Change icon of marker clicked when you have multiple markers

I am trying to change the marker icon when the marker is clicked the problem is the code below only changes the last marker I added to the map not the marker I am clicking on, so if I only had one marker it would work fine. I tried looking it up but all the examples I could find only work with 1 marker loaded in the map. I tried the listener two different ways the second one is commented out below the the first way and both just change the icon of the the last marker loaded.
<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: 95%;
}
/* Optional: Makes the sample page fill the window. */
html, body {
height: 95%;
margin: 0;
padding: 0;
}
<script src="https://maps.googleapis.com/maps/api/js?key=KEY&callback=initMap"
async defer></script>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
<script src="https://unpkg.com/#google/markerclustererplus#4.0.1/dist/markerclustererplus.min.js"></script>
<script>
let markers = [];
let map;
function loadMarkers(ssStr)
{
$.getJSON(ssStr, function(data) {
for (var i = 0; i < data.feed.entry.length; i++)
{
var latLng = new google.maps.LatLng(data.feed.entry[i]['gsx$lat']['$t'],
data.feed.entry[i]['gsx$long']['$t']);
var marker = new google.maps.Marker({
position: latLng,
map: map,
label:data.feed.entry[i]['gsx$structure']['$t'],
icon: { url: "http://maps.google.com/mapfiles/ms/icons/red.png" }
});
markers.push(marker);
google.maps.event.addListener(marker, 'click', function() {
//Change the marker icon
marker.setIcon('http://maps.google.com/mapfiles/ms/icons/green.png');
});
/* marker.addListener("click", (event) => {
marker.setIcon('http://maps.google.com/mapfiles/ms/icons/green.png');
}); */
}
var latLng = new google.maps.LatLng(data.feed.entry[0]['gsx$lat']['$t'],
data.feed.entry[0]['gsx$long']['$t']);
map.setCenter(latLng);
});
}
function initMap() {
console.log("initMap");
var mapOptions = {
zoom: 10,
center: new google.maps.LatLng(41.5, -72)
};
map = new google.maps.Map(document.getElementById('map'), mapOptions);
loadMarkers("http://spreadsheets.google.com/feeds/list/SSID/od6/public/values?alt=json");
}
</script>
</head>
<body>
<div id="map"></div>
</body>
</html>

Javascript GoogleMaps API Animation Onclick for Array of points

I've searched the web but can't seem to locate an answer for my issue. I believe I'm close but just can't get this to work as intended.
I'd like to plot an array of locations on a google map and start with the DROP animation, then when a user clicks a point, I'd like it to bounce.
My current code does 1/2 the job, however, when you click it's targeting the last value in my array. The BOUNCE animation works but it doesn't seem to be applied to all values in my array. Can you point at what I'm missing in the code?
Thanks for all the help!
<html>
<head>
<!-- styles put here, but you can include a CSS file and reference it instead! -->
<style type="text/css">
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#map {
height: 100%;
}
</style>
</head>
<body>
<div id="map"></div>
<script type="text/javascript">
// Create a map variable
var map;
var markers = [];
// Function to initialize the map within the map div
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 40.74135, lng: -73.99802},
zoom: 10
});
// Create a single latLng literal object.
var locations = [
{title: 'Beer', location: new google.maps.LatLng(47.666633, -122.371453)},
{title: 'Home', location: new google.maps.LatLng(47.613141, -122.320587)},
{title: 'Work', location: new google.maps.LatLng(47.624812, -122.315134)}
];
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < locations.length; i++) {
var position = locations[i].location;
var title = locations[i].title;
var marker = new google.maps.Marker({
map: map,
position: position,
title: title,
animation: google.maps.Animation.DROP,
id: i
});
bounds.extend(marker.position);
google.maps.event.addListener(marker, 'click', function(){
if (marker.getAnimation() !== null) {
marker.setAnimation(null);
} else {
marker.setAnimation(google.maps.Animation.BOUNCE);
}
});
// markers.push(marker);
}
map.fitBounds(bounds);
}
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=&v=3&callback=initMap">
</script>
</body>
</html>
One option would be to use this inside the click event listener function to reference the clicked marker.
google.maps.event.addListener(marker, 'click', function(){
if (this.getAnimation() !== null) {
this.setAnimation(null);
} else {
this.setAnimation(google.maps.Animation.BOUNCE);
}
});
(you can also use function closure)

Google Maps API: Want geolocation to click automatically on data layer below

I am trying to build a map-based site that identifies a user's geolocation, draws a marker at his/her position, and then uses that marker/location to click on a data layer (in this case, a GeoJSON layer). Essentially, the user's location should trigger an infowindow automatically if he or she is located on an area delineated by the geojson file. Ideally, each time the user changes location it will be clicking the map to check this GeoJSON layer for info.
So far, I can get the user's location successfully. The map centers on that location. And manual clicks on the GeoJSON layer also populate the info window correctly. But it's not clicking automatically when getting the user location.
I've seen lots of examples where a forced click on a marker takes place, but I can't seem to find one that clicks a data layer. Unfortunately I'm more of a GIS person assigned to a coding job on this, which is way out of my league, so I'm struggling to figure out where I'm going wrong with this.
Here's the script, perhaps I'm making a mistake here:
$<script type="text/javascript">
//centers the map on Iowa City
var map,
currentPositionMarker,
mapCenter = new google.maps.LatLng(41.661354, -91.534729),
map;
function initializeMap()
{
map = new google.maps.Map(document.getElementById('map_canvas'), {
zoom: 18,
center: mapCenter,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
map.data.loadGeoJson('test2.json');
map.data.setStyle({
strokeColor: '#2687bf',
strokeWeight: 5
});
map.data.addListener('click', function(event) {
document.getElementById('info-box').textContent =
event.feature.getProperty('description');
});
}
function locError(error) {
// the current position could not be located
alert("The current position could not be found!");
}
function setCurrentPosition(pos) {
currentPositionMarker = new google.maps.Marker({
map: map,
draggable: true,
position: new google.maps.LatLng(
pos.coords.latitude,
pos.coords.longitude
),
title: "Current Position"
});
new google.maps.event.trigger( 'test2.json', 'click' );
map.panTo(new google.maps.LatLng(
pos.coords.latitude,
pos.coords.longitude
));
}
function displayAndWatch(position) {
// set current position
setCurrentPosition(position);
// watch position
watchCurrentPosition();
}
function watchCurrentPosition() {
var positionTimer = navigator.geolocation.watchPosition(
function (position) {
setMarkerPosition(
currentPositionMarker,
position
);
});
}
function setMarkerPosition(marker, position) {
marker.setPosition(
new google.maps.LatLng(
position.coords.latitude,
position.coords.longitude)
);
}
function initLocationProcedure() {
initializeMap();
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(displayAndWatch, locError);
} else {
alert("Your browser does not support the Geolocation API");
}
}
$(document).ready(function() {
initLocationProcedure();
});
</script>
</head>
<body>
<div id="map_canvas" style="height:600px;"></div>
<div id="info-box" style="height:250px;">INFO</div>
</body>
</html>
And here are links to my JSON and full HTML file for this:
https://sites.google.com/site/ecocritkml/coding
The JSON is obviously specific to Iowa City, Iowa, but it could be modified easily in a text editor. Any ideas would be really helpful here.
I think I got it.
I had to use a few tricks (some maybe a little dirty)
I put a 500ms delay with setTimeout; this could have been done more elegantly, no doubt
I make a temporary polygon, because it permits to use containsLocation()
I don't invoke a click, but there is a loop over the polygon features, I read the description there, and set it to the div
..
<!doctype html>
<html lang="en">
<head>
<title>Google maps</title>
<script src="http://code.jquery.com/jquery-1.8.2.min.js"></script>
<script type="text/javascript" src=http://maps.google.com/maps/api/js?v=3&sensor=true&language=en"></script>
<style>
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#map_canvas {
height: 100%;
}
#info-box {
background-color: white;
border: 1px solid black;
bottom: 30px;
height: 20px;
padding: 10px;
position: absolute;
left: 30px;
}
</style>
<script type="text/javascript">
//centers the map on Iowa City
var map,
currentPositionMarker,
mapCenter = new google.maps.LatLng(41.661354, -91.534729),
map;
function initializeMap() {
map = new google.maps.Map(document.getElementById('map_canvas'), {
zoom: 18,
center: mapCenter,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
map.data.loadGeoJson('test2.json');
map.data.setStyle({
strokeColor: '#2687bf',
strokeWeight: 5
});
map.data.addListener('click', function(event) {
document.getElementById('info-box').textContent = event.feature.getProperty('description');
});
}
function locError(error) {
// the current position could not be located
}
function setCurrentPosition(pos) {
currentPositionMarker = new google.maps.Marker({
map: map,
draggable: true,
position: new google.maps.LatLng(
pos.coords.latitude,
pos.coords.longitude
),
title: "Current Position"
});
// Wait half a second, then take a loop of the features, see if the marker is inside one of them
setTimeout(function() {
map.data.forEach(function(feature){
var figure = feature.getGeometry();
if(figure.getType() == 'Polygon') {
// make a temporary polygon, see if the marker is inside
var tempPolygon = new google.maps.Polygon({
paths: figure.getAt(0).getArray(), // #see http://stackoverflow.com/questions/33249127/using-containslocation-with-a-google-maps-data-polygon
map: null
});
if(google.maps.geometry.poly.containsLocation(currentPositionMarker.getPosition(), tempPolygon)) {
// marker is inside this feature
// invoke a click. well, just pretend ...
document.getElementById('info-box').textContent = feature.getProperty('description');
}
}
var b;
})
}, 500);
map.panTo(new google.maps.LatLng(
pos.coords.latitude,
pos.coords.longitude
));
}
function displayAndWatch(position) {
// set current position
setCurrentPosition(position);
// watch position
watchCurrentPosition();
}
function watchCurrentPosition() {
var positionTimer = navigator.geolocation.watchPosition(function (position) {
setMarkerPosition(
currentPositionMarker,
position
);
});
}
function setMarkerPosition(marker, position) {
marker.setPosition(
new google.maps.LatLng(
position.coords.latitude,
position.coords.longitude
)
);
// now we see if the marker is inside one of the polygons
var a = 0;
}
function initLocationProcedure() {
initializeMap();
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(displayAndWatch, locError);
}
else {
// alert("Your browser does not support the Geolocation API");
}
}
$(document).ready(function() {
initLocationProcedure();
});
</script>
</head>
<body>
<div id="map_canvas" style="height:600px;"></div>
<div id="info-box" style="height:250px;">INFO</div>
</body>
</html>

Multiple Google Maps icons?

I'm trying to combine the following two blocks of codes together.
but for some reason, when i load the page in the browser, First the second blocks of code loads the marker on the map and then the page refreshes and the first blocks of code loads on the map!
This is my entire code:
<!DOCTYPE html>
<html>
<head>
<title>Google maps</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;
geocoder = new google.maps.Geocoder();
function initialize() {
var mapOptions = {
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map-canvas'),mapOptions);
codeAddress();
}
function codeAddress() {
var address = '<?= $_GET['location'] ?>';
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({
icon: 'meicon.png',
map: map,
position: results[0].geometry.location
});
} else {
alert("Error loading map");
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas"></div>
<script type="text/javascript">
var locations = [
['Bondi Beach', 51.5033631,-0.1276253, 1]
];
var maps = new google.maps.Map(document.getElementById('map-canvas'), {
zoom: 15,
center: new google.maps.LatLng(51.5033630,-0.1276250),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow();
var markers, i;
for (i = 0; i < locations.length; i++) {
markers = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: maps
});
google.maps.event.addListener(markers, 'click', (function(markers, i) {
return function() {
infowindow.setContent(locations[i][0]);
infowindow.open(map, markers);
}
})(markers, i));
}
</script>
</body>
</html>
could someone please advise on this issue?
Thanks in advance.
It's probably because you're calling the geocoder on the address in the first block, which is an async call to google to check the address. While the code is talking to google the page runs the second code block. When that call returns it runs the rest of the code in the first block, which sets the center of the map.
The reason is simple you are loading two map the first called in <head> script what build a map in map-canvas named map. the second in body script you create another map named maps and this too create in map-canvas.You need only a working map and with this do what you nedd.

How to highlight map marker upon selection of an html element

Need help with getting html elements interact with google maps.
I have 2 sections on a Web page. On the right side of the page, I have a map showing multiple markers. On the left side of the page, I have a list with addresses which correspond to the markers in the map.
Please suggest pointers on how to highlight a marker when the corresponding address is selected from the list on the left side of the page.
Okay, I made it with hover() . Hovering over the div highlights the marker
<head>
<style>
html, body, #map-canvas {
height: 400px;
margin: 0px;
padding: 0px
}
#markers_info .marker {
height: 40px;
cursor: pointer;
}
</style>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?"></script>
<script>
/**
jQuery events
*/
$(document).ready(function() {
// initiate Google maps
initialize();
// make a .hover event
$('#markers_info .marker').hover(
// mouse in
function () {
// first we need to know which <div class="marker"></div> we hovered
var index = $('#markers_info .marker').index(this);
markers[index].setIcon(highlightedIcon());
},
// mouse out
function () {
// first we need to know which <div class="marker"></div> we hovered
var index = $('#markers_info .marker').index(this);
markers[index].setIcon(normalIcon());
}
);
});
/**
Google Maps stuff
*/
var markerData = [ // the order of these markers must be the same as the <div class="marker"></div> elements
{lat: 50.84498605, lng: 4.349977747, title: 'Manneken Pis'},
{lat: 50.84848913, lng: 4.354053363, title: 'Jeanneke Pis'},
{lat: 50.84673465, lng: 4.352466166, title: 'Grand Place'}
];
var map;
var markers = [];
var mapOptions = {
zoom: 15,
center: new google.maps.LatLng(50.84673465,4.352466166), // Brussels, Belgium
mapTypeId: google.maps.MapTypeId.ROADMAP
};
function initialize() {
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
for (var i=0; i<markerData.length; i++) {
markers.push(
new google.maps.Marker({
position: new google.maps.LatLng(markerData[i].lat, markerData[i].lng),
title: markerData[i].title,
map: map,
icon: normalIcon()
})
);
}
}
// functions that return icons. Make or find your own markers.
function normalIcon() {
return {
url: 'http://1.bp.blogspot.com/_GZzKwf6g1o8/S6xwK6CSghI/AAAAAAAAA98/_iA3r4Ehclk/s1600/marker-green.png'
};
}
function highlightedIcon() {
return {
url: 'http://steeplemedia.com/images/markers/markerGreen.png'
};
}
//google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas"></div>
<div id="markers_info">
<div class="marker">Manneken Pis, 50.84498605,4.349977747</div>
<div class="marker">Jeanneke Pis, 50.84848913,4.354053363</div>
<div class="marker">Grand Place, 50.84673465,4.352466166</div>
</div>
</body>

Categories

Resources