Google Map - Getting co-ords out - google-maps

<Body>
<!--Button to pull out marker co-ords-->
<p><button onclick="document.getElementById('latlnginpara').innerHTML = map.marker.getBounds()">Get map bounds</button></p>
<!--This is where the co-ords will sit for now-->
<div id="latlnginpara"></div>
<!--This plots a slot for the map-->
<div id="map" style="width:100%;height:500px;"></div>
<!--Now starts the Map fun-->
<script>
function myMap() {
var mapCanvas = document.getElementById("map");
var myCenter=new google.maps.LatLng(51.508742,-0.120850);
var mapOptions = {
center: myCenter,
zoom: 5,
zoomControl: true,
mapTypeControl: true,
scaleControl: true,
streetViewControl: true,
overviewMapControl: true,
rotateControl: true,
};
var map = new google.maps.Map(mapCanvas, mapOptions);
//1 marker bit
var marker;
function placeMarker(location) {
if ( marker ) {
marker.setPosition(location);
} else {
marker = new google.maps.Marker({
position: location,
map: map
});
}
}
google.maps.event.addListener(map, 'click', function(event) {
placeMarker(event.latLng);
});
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyD5WIxyWvYfFU3vY27DM7mc-JClPwPLB0A&callback=myMap"></script>
</Body>
For the life of me, I'm trying to get co-ordinates OUT of google maps from a marker, for later use in a database......
I have most of the code but I can't seem to get it to work together!
This super brain helped someone get 1 marker that updates
GoogleMaps v3 API Create only 1 marker on click
This code pulled out co-ordinates into the body of the page.
https://www.w3schools.com/graphics/tryit.asp?filename=trymap_ref_getbounds
But all together....
Your help would be much appreciated!!!

You can simply get the marker's coordinates using .lat() and .lng().
var marker, map;
function placeMarker(location) {
if (marker) {
marker.setPosition(location);
} else {
marker = new google.maps.Marker({
position: location,
map: map
});
}
document.getElementById('location').textContent = location.toString();
document.getElementById('lat').textContent = location.lat(); // get latitude
document.getElementById('lng').textContent = location.lng(); // get longitude
}
function myMap() {
var mapCanvas = document.getElementById("map");
var myCenter = new google.maps.LatLng(51.508742, -0.120850);
var mapOptions = {
center: myCenter,
zoom: 5,
zoomControl: true,
mapTypeControl: true,
scaleControl: true,
streetViewControl: true,
overviewMapControl: true,
rotateControl: true,
};
map = new google.maps.Map(mapCanvas, mapOptions);
google.maps.event.addListener(map, 'click', function(event) {
placeMarker(event.latLng);
});
}
myMap();
<!--Button to pull out marker co-ords-->
<p><button onclick="document.getElementById('latlnginpara').innerHTML = map.marker.getBounds()">Get map bounds</button></p>
<p id='location'></p>
<p id='lat'></p>
<p id='lng'></p>
<!--This is where the co-ords will sit for now-->
<div id="latlnginpara"></div>
<!--This plots a slot for the map-->
<div id="map" style="width:100%;height:500px;"></div>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyD5WIxyWvYfFU3vY27DM7mc-JClPwPLB0A&"></script>

Many thanks! This is the answer
var marker, map;
function placeMarker(location) {
if (marker) {
marker.setPosition(location);
} else {
marker = new google.maps.Marker({
position: location,
map: map
});
}
document.getElementById('location').textContent = location.toString();
document.getElementById('lat').textContent = location.lat(); // get latitude
document.getElementById('lng').textContent = location.lng(); // get longitude
}
function myMap() {
var mapCanvas = document.getElementById("map");
var myCenter = new google.maps.LatLng(51.508742, -0.120850);
var mapOptions = {
center: myCenter,
zoom: 5,
zoomControl: true,
mapTypeControl: true,
scaleControl: true,
streetViewControl: true,
overviewMapControl: true,
rotateControl: true,
};
map = new google.maps.Map(mapCanvas, mapOptions);
google.maps.event.addListener(map, 'click', function(event) {
placeMarker(event.latLng);
});
}
myMap();
<!--Button to pull out marker co-ords-->
<p><button onclick="document.getElementById('latlnginpara').innerHTML = map.marker.getBounds()">Get map bounds</button></p>
<p id='location'></p>
<p id='lat'></p>
<p id='lng'></p>
<!--This is where the co-ords will sit for now-->
<div id="latlnginpara"></div>
<!--This plots a slot for the map-->
<div id="map" style="width:100%;height:500px;"></div>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyD5WIxyWvYfFU3vY27DM7mc-JClPwPLB0A&"></script>

Related

Google Maps V3 - Load different markers on click function

So I have the following in my HTML which represents regions in the UK:-
<h4 id="google-ne" class="active">The North East</h4>
<h4 id="google-nw">The North West</h4>
<h4 id="google-ea">East Anglia</h4>
<h4 id="google-em">East Midlands</h4>
<h4 id="google-tm">The Midlands</h4>
<h4 id="google-wm">West Midlands</h4>
<h4 id="google-ld">London</h4>
<h4 id="google-se">South East</h4>
<h4 id="google-sw">South West</h4>
<h4 id="google-ws">Wales</h4>
<h4 id="google-sl">Scotland</h4>
and then the marker lat / long and region are displayed in HTML as follows:-
<div class="marker" data-lat="52.559437" data-lng="-2.1493073" data-region="West Midlands"></div>
<div class="marker" data-lat="51.646145" data-lng="-0.45614472" data-region="South East"></div>
and so on, there are about 400 markers.
I am currently using the following code to display all markers on the map which is working fine:-
var center = new google.maps.LatLng(51.5280359,-0.1304897);
function initialize_map() {
var map;
var bounds = new google.maps.LatLngBounds();
var mapOptions = {
mapTypeId: 'roadmap'
};
var markerBounds = new google.maps.LatLngBounds();
var w = Math.max(document.documentElement.clientWidth, window.innerWidth || 0);
var isDraggable = w > 480 ? true : false;
var mapOptions = {
zoom: 8,
center: center,
//draggable: isDraggable,
//mapTypeControl: false,
//draggable: false,
zoomControl: true,
mapTypeControl: true,
scaleControl: true,
scrollwheel: true,
navigationControl: true,
streetViewControl: true,
disableDefaultUI: true
};
var map = new google.maps.Map(document.getElementById('map'),
mapOptions);
// Multiple Markers
// Loop through our array of markers & place each one on the map
$('.marker').each(function() {
var location = {
latLng: new google.maps.LatLng(
$( this ).data( 'lat' ),
$( this ).data( 'lng' )
),
//title: $( this ).find( 'h2' ).html()
};
new google.maps.Marker( {
map: map,
position: location.latLng,
//title: $( this ).data( 'desc' )
} );
markerBounds.extend( location.latLng );
});
// Override our map zoom level once our fitBounds function runs (Make sure it only runs once)
var boundsListener = google.maps.event.addListener((map), 'bounds_changed', function(event) {
this.setZoom(14);
google.maps.event.removeListener(boundsListener);
});
var styles = [
/* Black & White {"featureType":"water","elementType":"geometry","stylers":[{"color":"#e9e9e9"},{"lightness":17}]},{"featureType":"landscape","elementType":"geometry","stylers":[{"color":"#f5f5f5"},{"lightness":20}]},{"featureType":"road.highway","elementType":"geometry.fill","stylers":[{"color":"#ffffff"},{"lightness":17}]},{"featureType":"road.highway","elementType":"geometry.stroke","stylers":[{"color":"#ffffff"},{"lightness":29},{"weight":0.2}]},{"featureType":"road.arterial","elementType":"geometry","stylers":[{"color":"#ffffff"},{"lightness":18}]},{"featureType":"road.local","elementType":"geometry","stylers":[{"color":"#ffffff"},{"lightness":16}]},{"featureType":"poi","elementType":"geometry","stylers":[{"color":"#f5f5f5"},{"lightness":21}]},{"featureType":"poi.park","elementType":"geometry","stylers":[{"color":"#dedede"},{"lightness":21}]},{"elementType":"labels.text.stroke","stylers":[{"visibility":"on"},{"color":"#ffffff"},{"lightness":16}]},{"elementType":"labels.text.fill","stylers":[{"saturation":36},{"color":"#333333"},{"lightness":40}]},{"elementType":"labels.icon","stylers":[{"visibility":"off"}]},{"featureType":"transit","elementType":"geometry","stylers":[{"color":"#f2f2f2"},{"lightness":19}]},{"featureType":"administrative","elementType":"geometry.fill","stylers":[{"color":"#fefefe"},{"lightness":20}]},{"featureType":"administrative","elementType":"geometry.stroke","stylers":[{"color":"#fefefe"},{"lightness":17},{"weight":1.2}]} */
/* Colour*/ {"featureType":"landscape.man_made","elementType":"geometry.fill","stylers":[{"saturation":"-63"},{"lightness":"23"}]},{"featureType":"landscape.natural","elementType":"geometry.fill","stylers":[{"saturation":"-100"},{"lightness":"25"}]},{"featureType":"landscape.natural.terrain","elementType":"geometry.fill","stylers":[{"saturation":"0"}]},{"featureType":"poi.park","elementType":"geometry.fill","stylers":[{"saturation":"0"},{"color":"#95bf97"},{"lightness":"59"}]},{"featureType":"poi.school","elementType":"geometry.fill","stylers":[{"lightness":"5"},{"hue":"#ff0000"},{"saturation":"-100"}]},{"featureType":"poi.sports_complex","elementType":"geometry.fill","stylers":[{"lightness":"5"},{"saturation":"-100"}]},{"featureType":"road.local","elementType":"geometry.fill","stylers":[{"saturation":"-85"},{"lightness":"12"}]}
];
map.setOptions({styles: styles});
}
initialize_map();
}
What I want to do now is on click of say 'West Midlands' #google-wm, it removes all markers currently on the map and then only shows markers where the data-region == 'West Midlands'
How is it possible to do this?
Thanks in advance.
You could do something like that. Code is commented for the parts that I have added/changed.
var markers = [];
var map;
function initialize() {
var myLatLng = new google.maps.LatLng(52, -1);
var mapOptions = {
zoom: 6,
center: myLatLng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
$('.marker').each(function() {
var location = {
latLng: new google.maps.LatLng(
$(this).data('lat'),
$(this).data('lng')
),
};
var marker = new google.maps.Marker({
map: map,
position: location.latLng,
});
// Register click event
$(this).on('click', function() {
clickMarker($(this).data('region'));
});
// Push marker and region to markers array
markers.push({
'marker': marker,
'region': $(this).data('region')
});
});
}
function clickMarker(region) {
// Loop through markers array
for (var i = 0; i < markers.length; i++) {
// If marker region = selected region, display it
if (markers[i].region === region) {
markers[i].marker.setMap(map);
} else {
// Hide marker from different region
markers[i].marker.setMap(null);
}
}
}
initialize();
#map-canvas {
height: 150px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="map-canvas"></div>
<div class="marker" data-lat="52.5" data-lng="-2.1" data-region="West Midlands">Marker 1 - WM</div>
<div class="marker" data-lat="52.6" data-lng="-2.2" data-region="West Midlands">Marker 2 - WM</div>
<div class="marker" data-lat="51.6" data-lng="-0.4" data-region="South East">Marker 3 - SE</div>
<div class="marker" data-lat="51.7" data-lng="-0.5" data-region="South East">Marker 4 - SE</div>
<script src="https://maps.googleapis.com/maps/api/js"></script>

Creating Geotagged Marker Alongside a Multiple Markers in Google Maps

I've been stuck on this issue for a while now and could really use some help. In a Google Map, I have a list of markers which are being treated as a markerArray, with their own custom icons. But along with displaying those markers, I would like for it to create a marker which is placed at the users geotagged location. I have tried merging the suggestions I've come across here on stack overflow, and have successfully gotten the users browser to center the map based off of geolocation, but whenever I try to add a marker outside of the standard var=locations, all of the markers disappear. I am providing my working code, which simply lacks the feature to add the "current location" marker. If anyone has any input, I'd be thrilled.
var map = null;
var markerArray = [];
function initialize() {
var myOptions = {
zoom: 13,
center: new google.maps.LatLng(40.746613, -73.990109),
mapTypeControl: false,
navigationControl: false,
streetViewControl: false,
zoomControl: false,
styles: [{featureType:"landscape",stylers:[{saturation:-100},{lightness:65},{visibility:"on"}]},{featureType:"poi",stylers:[{saturation:-100},{lightness:51},{visibility:"simplified"}]},{featureType:"road.highway",stylers:[{saturation:-100},{visibility:"simplified"}]},{featureType:"road.arterial",stylers:[{saturation:-100},{lightness:30},{visibility:"on"}]},{featureType:"road.local",stylers:[{saturation:-100},{lightness:40},{visibility:"on"}]},{featureType:"transit",stylers:[{saturation:-100},{visibility:"simplified"}]},{featureType:"administrative.province",stylers:[{visibility:"off"}]/**/},{featureType:"administrative.locality",stylers:[{visibility:"off"}]},{featureType:"administrative.neighborhood",stylers:[{visibility:"on"}]/**/},{featureType:"water",elementType:"labels",stylers:[{visibility:"on"},{lightness:-25},{saturation:-100}]},{featureType:"water",elementType:"geometry",stylers:[{hue:"#ffff00"},{lightness:-25},{saturation:-97}]}]
};
map = new google.maps.Map(document.getElementById('map'), myOptions);
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
initialLocation = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
map.setCenter(initialLocation);
});
}
google.maps.event.addListener(map, 'click', function() {
infowindow.close();
});
var locations = [
['90 West Apartment', 40.709943, -74.014430, 7, 'images/pin2.png'],
['Caffe Vita', 40.719652, -73.988411, 6, 'images/pin1.png'],
['Croxleys Ale House', 40.722480, -73.983386, 5, 'images/pin1.png'],
['Grays Papaya', 40.778291, -73.981829, 4, 'images/pin2.png'],
['The Back Room', 40.718723, -73.986913, 3, 'images/pin1.png'],
['MUD Coffee', 40.729912, -73.990678, 2, 'images/pin1.png'],
['Nurse Bettie', 40.718820, -73.986863, 1, 'pin2.png']];
for (var i = 0; i < locations.length; i++) {
createMarker(new google.maps.LatLng(locations[i][1], locations[i][2]),locations[i][0], locations[i][3], locations[i][4]);
}
mc.addMarkers(markerArray, true);
}
var infowindow = new google.maps.InfoWindow({
size: new google.maps.Size(150, 50)
});
function createMarker(latlng, myTitle, myNum, myIcon) {
var contentString = myTitle;
var marker = new google.maps.Marker({
position: latlng,
map: map,
icon: myIcon,
zIndex: Math.round(latlng.lat() * -100000) << 5,
title: myTitle
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(contentString);
infowindow.open(map, marker);
});
markerArray.push(marker);
}
window.onload = initialize;
Let's try this.
Put this in your initialize(): navigator.geolocation.getCurrentPosition(showPosition);
Then define showPosition:
var showPosition = function (position) {
var userLatLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
// Do whatever you want with userLatLng.
var marker = new google.maps.Marker({
position: userLatLng,
title: 'Your Location',
map: map
});
}

Changing the Google Maps marker/infowindow position

I'm currently using this snippet to display my map on a certain page
<div id="map_canvas" style="width: 400px; height: 300px;"></div>
<div class="map_js">
<script src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script>
var myLatlng = new google.maps.LatLng(0, 0);
var mapOptions = {
zoom: 15,
center: myLatlng,
scrollwheel: true,
scaleControl: false,
disableDefaultUI: false,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
var geocoder_map = new google.maps.Geocoder();
var address = 'New York';
geocoder_map.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: map.getCenter()
});
var contentString = 'Hello World New York is the most populous city in the United States.';
var infowindow = new google.maps.InfoWindow({
content: contentString,
maxWidth: 200
});
google.maps.event.addListener(marker, 'click', function () {
infowindow.open(map, marker)
});
infowindow.open(map, marker)
} else {
alert('Geocode was not successful for the following reason: ' + status)
}
});
</script>
</div>
but, as you can see in this image http://d.pr/i/whoI the infowindow is somehow overlapping a bit with the default maps UI.
Does someone know how to solve this issue perhaps?
Best Regards, Jen

How do I use Google map data in other form elements?

How do I take Google map coordinates from the map and automatically populate another form element?
This is my form: http://www.barbadosphonebook.com/list-your-business-for-free/. At the bottom there is a Google map which, on-click, displays the coordinates. I would love it to also populate the element below with the coordinate data.
My map code:
<script type="text/javascript"
src="http://maps.google.com/maps/api/js?sensor=true">
</script>
<script type="text/javascript">
function initialize() {
var latlng = new google.maps.LatLng(13.175771, -59.556885);
var myOptions = {
zoom: 10,
center: latlng,
navigationControl: true,
mapTypeControl: true,
scaleControl: true,
mapTypeId: google.maps.MapTypeId.HYBRID
};
var map = new google.maps.Map(document.getElementById("map_canvas"),myOptions);
//
var contentString = '<strong>Copy the numbers between the brackets</strong><br />';
google.maps.event.addListener(map, 'click', function(event) {
new google.maps.InfoWindow ( { position: event.latLng, content: contentString+event.latLng.toString() } ).open(map);
});
}
</script>
You could try changing your map click listener to this:
google.maps.event.addListener(map, 'click', function(event) {
new google.maps.InfoWindow ( { position: event.latLng, content: contentString+event.latLng.toString() } ).open(map);
$('.ginput_container input').val(event.latLng.toString());
});

Google Maps API V3: How to jump to a specific marker from outside the map?

I have a map with two markers on it.
The initial view of the map only shows one marker, and I want to provide a link next to the map that will move the map to the 2nd marker when clicked.
Here's a demo of what I want, using v2 of the API: http://arts.brighton.ac.uk/contact-university-of-brighton-faculty-of-arts (note the links below the map)
Here's what I have so far:
<script type="text/javascript">
function initialize() {
var latlng = new google.maps.LatLng(50.823817, -0.135634);
var myOptions = {
zoom: 13,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
} ,
scaleControl: false
};
var map = new google.maps.Map(document.getElementById("map"), myOptions);
// 1st marker
var marker1 = new google.maps.Marker({ position: new google.maps.LatLng(50.823817, -0.135634), map: map, title: 'my title' });
var infowindow = new google.maps.InfoWindow({ content: 'my window content' });
google.maps.event.addListener(marker1, 'click', function() { infowindow.open(map, marker1); });
// 2nd marker
var marker2 = new google.maps.Marker({ position: new google.maps.LatLng(51.5262405, -0.074549), map: map, title: 'my 2nd title'});
var infowindow2 = new google.maps.InfoWindow({ content: 'content for my 2nd window' });
google.maps.event.addListener(marker2, 'click', function() { infowindow2.open(map, marker2); });
}
</script>
So what I'd like to add is a link to marker2, to move the map some 50-odd miles up,
e.g. Second location.
How would I do this?
Use addDomListener to add a click event to the link that will move the map to that marker (you'll also need to add an id to the link tag so you can reference it in code):
Edit: Set the event in a initialization function:
<head>
<script type="text/javascript">
function initialize() {
var myLatlng = new google.maps.LatLng(-34.397, 150.644);
var myOptions = {
zoom: 8,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var marker2 = new google.maps.Marker({ position: new google.maps.LatLng(51.5262405, -0.074549), map: map, title: 'my 2nd title'});
google.maps.event.addDomListener(document.getElementById("linkID"), "click", function(ev) {
map.setCenter(marker2.getPosition());
}
}
</script>
</head>
<body style="margin:0px; padding:0px;" onload="initialize()">
Second place
<div id="map_canvas" style="width:100%; height:100%"></div>
</body>