Auto filled search box - javascript

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.

Related

How to Open email application while clicking on the email ID in google Maps InfoWindow

I want to Open the email application with prepopulated subject 'SUBJECT' while clicking on the email ID in the google Maps Info window. Below is the code i wrote to Display the email ID and I am not sure how to proceed further.
function init(resp) {
var mapProp = {
center : new google.maps.LatLng(resp.data[0].Lat,
resp.data[0].Lon),
zoom : 7,
};
var map = new google.maps.Map(document.getElementById("googleMap"),
mapProp);
$.each(resp.data, function(index, value) {
var myLatlng = new google.maps.LatLng(value.Lat, value.Lon);
var marker = new google.maps.Marker({
position : myLatlng,
label : value['Number'],
content : "Phone: " + value['Phone Number'] + '<br>'
+ "E-Mail: " + ''+ value['E-Mail'] +''
});
var infowindow = new google.maps.InfoWindow({
content : "Phone: " + value['Phone Number'] + '<br>'
+ "E-Mail: " + ''+ value['E-Mail'] +''
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map, marker);
});
// To add the marker to the map, call setMap();
marker.setMap(map);
});
You can use the mailto of JavaScript. You can change the values of different parameters to suit your email.
So in your code, you can put something like this as your content in your InfoWindow:
var infowindow = new google.maps.InfoWindow({
content :'<div id="content">'+
'<a href="mailto:username#example.com?subject=Subject&body=message%20goes%20here">'+
'Click to Email</a> '+
'</div>'
});
The following is a sample code. To see how this works, you can copy and save it as html file and run it in your browser. Please note to change your API Key:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Info Windows</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>
// This example displays a marker at the center of Australia.
// When the user clicks the marker, an info window opens.
function initMap() {
var uluru = {lat: -25.363, lng: 131.044};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: uluru
});
var contentString = '<div id="content">'+
'<a href="mailto:username#example.com?subject=Subject&body=message%20goes%20here">'+
'Click to Email</a> '+
'</div>';
var infowindow = new google.maps.InfoWindow({
content: contentString
});
var marker = new google.maps.Marker({
position: uluru,
map: map,
title: 'Uluru (Ayers Rock)'
});
marker.addListener('click', function() {
infowindow.open(map, marker);
});
}
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=CHANGE_API_KEY_HERE&callback=initMap">
</script>
</body>
</html>
Hope this helps!

Google Map get current location that can be changed by dragging the pin

This is my first post so i'm sorry if it has been asked before.
I have a form users fill out on mobile devices which captures there longitude and latitude using JavaScript geolocation. this isn't always the most accurate so I am trying to combine geolocation and google map draggable pin.
So the user opens the page, geolocation enters the current lon and lat in the script below, if its wrong they can then drag the pin to the right location which updates the text fields.
I have tried every thing and have had mixed results...if someone could help me out that would be great.
I hope this makes sense...if not im happy to explain more
The script below enables you to drag the pin and updates the two text field with the lon and lat.
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
<input type="text" id="latitude" placeholder="latitude">
<input type="text" id="longitude" placeholder="longitude">
<div id="map" style="width:500px; height:500px"></div>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script>
function initialize() {
var $latitude = document.getElementById('latitude');
var $longitude = document.getElementById('longitude');
var latitude = 50.715591133433854
var longitude = -3.53485107421875;
var zoom = 7;
var LatLng = new google.maps.LatLng(latitude, longitude);
var mapOptions = {
zoom: zoom,
center: LatLng,
panControl: false,
zoomControl: false,
scaleControl: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById('map'),mapOptions);
var marker = new google.maps.Marker({
position: LatLng,
map: map,
title: 'Drag Me!',
draggable: true
});
google.maps.event.addListener(marker, 'dragend', function(marker){
var latLng = marker.latLng;
$latitude.value = latLng.lat();
$longitude.value = latLng.lng();
});
}
initialize();
</script>
</body>
</html>
<script src="http://maps.googleapis.com/maps/api/js"></script>
<script type="text/javascript">
function initialize() {
var map;
var position = new google.maps.LatLng(50.45, 4.45); // set your own default location.
var myOptions = {
zoom: 15,
center: position
};
var map = new google.maps.Map(document.getElementById("map-canvas"), myOptions);
// We send a request to search for the location of the user.
// If that location is found, we will zoom/pan to this place, and set a marker
navigator.geolocation.getCurrentPosition(locationFound, locationNotFound);
function locationFound(position) {
// we will zoom/pan to this place, and set a marker
var location = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
// var accuracy = position.coords.accuracy;
map.setCenter(location);
var marker = new google.maps.Marker({
position: location,
map: map,
draggable: true,
title: "You are here! Drag the marker to the exact location."
});
// set the value an value of the <input>
updateInput(location.lat(), location.lng());
// Add a "drag end" event handler
google.maps.event.addListener(marker, 'dragend', function() {
updateInput(this.position.lat(), this.position.lng());
});
}
function locationNotFound() {
// location not found, you might want to do something here
}
}
function updateInput(lat, lng) {
document.getElementById("my_location").value = lat + ',' + lng;
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
<style>
#map-canvas {
width: 500px;
height: 400px;
}
</style>
<div id="map-canvas"></div>
Location:<br>
<input id="my_location" readonly="readonly">
You can get the user location from the navigator.geolocation:
navigator.geolocation.getCurrentPosition(function (position) {
var pos = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
latPosition = position.coords.latitude;
longPosition = position.coords.longitude;
});
Then you can use these values to fill in your coordinates inputs and/or to place a marker on the map, as in my demo below.
JSFiddle demo

Debug my Google map Cluster Code

I am using this code to create a Google map with 3 points that are hidden within one and when the one marker is clicked thepoints either get merged into the one or they open up into 3 separate ones, however the map is not appearing can any one examine my code and see the potential problem?
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>favorite cities</title>
<style>
html, body, #map-canvas {
height: 100%;
margin: 0px;
padding: 0px
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script>
<script>
(function() {
window.onload = function(){
var options = {
zoom: 3,
center: new google.maps.LatLng(37.99, -93.77),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map'), options);
var mgr = new MarkerManager(map);
var A = new google.maps.Marker({
position: new google.maps.LatLng(37.99, -93.77),
icon: 'img/cluster.png'
});
google.maps.event.addListener(A, 'click', function() {
map.setZoom(7);
map.setCenter(Kloof.getPosition());
});
var Cities = [A];
var Schools = [
//SChool1
new google.maps.Marker({position: new google.maps.LatLng(38.99, -93.97)}),
//School2
new google.maps.Marker({position: new google.maps.LatLng(37.89, -94.77)}),
//School3
new google.maps.Marker({position: new google.maps.LatLng(37.79, -95.77)})
];
google.maps.event.addListener(mgr, 'loaded', function() {
agr.addMarkers(Cities, 11, 6);
agr.addMarkers(Schools, 6);
agr.refresh
});
};
})();
</script>
</head>
<body>
<div id="map-canvas"></div>
</body>
</html>
Change:
var map = new google.maps.Map(document.getElementById('map'), options);
To:
var map = new google.maps.Map(document.getElementById('map-canvas'), options);
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>favorite cities</title>
<style>
html, body, #map-canvas {
height: 100%;
margin: 0px;
padding: 0px
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script>
<script>
(function() {
window.onload = function(){
var options = {
zoom: 3,
center: new google.maps.LatLng(37.99, -93.77),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map-canvas'), options);
var mgr = new MarkerManager(map);
var A = new google.maps.Marker({
position: new google.maps.LatLng(37.99, -93.77),
icon: 'img/cluster.png'
});
google.maps.event.addListener(A, 'click', function() {
map.setZoom(7);
map.setCenter(Kloof.getPosition());
});
var Cities = [A];
var Schools = [
//SChool1
new google.maps.Marker({position: new google.maps.LatLng(38.99, -93.97)}),
//School2
new google.maps.Marker({position: new google.maps.LatLng(37.89, -94.77)}),
//School3
new google.maps.Marker({position: new google.maps.LatLng(37.79, -95.77)})
];
google.maps.event.addListener(mgr, 'loaded', function() {
agr.addMarkers(Cities, 11, 6);
agr.addMarkers(Schools, 6);
agr.refresh
});
};
})();
</script>
</head>
<body>
<div id="map-canvas"></div>
</body>
</html>
I changed the code to the following:
<
var schoolArray = []; //Global array to store the POINTS
var SchoolPoints = [[-29.788911, 30.852721, 'Thomas More College'], //I am creating a global array to store the MARKERS
[-29.781297, 30.838465, 'Kloof Senior Primary School'],
[-29.827008, 30.881706, 'Pinetown Boys HighSchool']];
function initialize() { //I am initializing the google map and how it will appear on my dashboard
var myOptions = {
zoom: 9,
center: new google.maps.LatLng(-29.807762, 30.854261),
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var mcOptions = { //this is where i determine BY GRID the amount of tiles that will determine if my schools points cluster or if they are separate and also the max zoom level the individual points are visual at
gridSize: 25,
maxZoom: 20
};
var mc = new MarkerClusterer(map, [], mcOptions); //this creates the blue cluster you see initially on the map
google.maps.event.addListener(map, 'click', function() { //upon click the map zooms in and displays the 3 schools with separate markers
infowindow.close();
});
// This is where the markers are added to the map and sorted into the cluster
for(var i=0; i<SchoolPoints.length; i++){ //This is where where i am setting up my markers on the map based off the number of elements within the points array
createMarker(new google.maps.LatLng(SchoolPoints[i][0], SchoolPoints[i][1]), SchoolPoints[i][2]);
}
mc.addMarkers(schoolArray , true); //now the markers are clustered together in the blue symbol
}
var infowindow = new google.maps.InfoWindow({ //I am determining the size of the info window that will be displayed by my school points
size: new google.maps.Size(500, 250)
});
function createMarker(latlng, html) { //this function is where i create the individual markers
var contentString = html;
var marker = new google.maps.Marker({
position: latlng,
map: map,
icon: '',
});
marker.setAnimation(google.maps.Animation.DROP); //I decided for aesthetic reasons i would like to see if i could animate the markers and so i added a drop animation
google.maps.event.addListener(marker, 'click', function() { //when clicking the markers their info windows are displayed
infowindow.setContent(contentString); //This sets the info window to have the content listed in the array visible
infowindow.open(map, marker);
});
schoolArray.push(marker);
}
window.onload = initialize;
​

Google Maps API showing blank map

I'm sure this is a basic problem but I've hit my head against the wall too many times now, so hopefully someone will take pity on me!
I have the following example but all it does is show a grayed out box, no map at all. Can anyone tell me why?
I've checked that I'm actually returning a result and it seems to be working fine.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title></title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<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 geocoder;
var map;
function initialize()
{
geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': "England"}, function(results, status)
{
if (status == google.maps.GeocoderStatus.OK)
{
var mapOptions = {
zoom: 8,
center: new google.maps.LatLng(results[0].geometry.location),
mapTypeId: google.maps.MapTypeId.ROADMAP
}
// Let's draw the map
map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
}
else
{
alert("Geocode was not successful for the following reason: " + status);
}
});
}
initialize();
</script>
</head>
<body onload="">
<div id="map-canvas" style="width: 320px; height: 480px;"></div>
</body>
</html>
Try resizing the browser window, give a shake to browser/drag it from browser tab with the cursor and you will see the map appearing.
From some strange reason in MVC partial view google map comes as blank, your map is working it just need to be resized.
Shaking a browser window with cursor sounds funny, but it works and I am not sure how to best describe it.
Thanks,
Anurag
=======================================================================
my final working code is below:
`
<script type="text/javascript">
$(document).ready(function () {
(function () {
var options = {
zoom: 6,
center: new google.maps.LatLng(-2.633333, 37.233334),
mapTypeId: google.maps.MapTypeId.TERRAIN,
mapTypeControl: false
};
// init map
var map = new google.maps.Map(document.getElementById('map_canvas'), options);
var arrLocation = [];
$("#markerDiv").find("div").each(function () {
var Lat = $(this).find("input[id='Latitude']").val();
var Lon = $(this).find("input[id='Longitude']").val();
var Id = $(this).find("input[id='Id']").val();
var AssessmentDet = $(this).find("input[id='AssessmentDateTime']").val();
var LocAcc = $(this).find("input[id='LocationAccuracy']").val();
var assessorName = $(this).find("input[id='AssessorName']").val();
var partnerName = $(this).find("input[id='PartnerName']").val();
arrLocation.push({
Id: Id,
Latitude: Lat,
Longitude: Lon,
AssessmentDate: AssessmentDet,
LocationAccuracy: LocAcc,
AssessorDetail: assessorName,
PartnerName: partnerName
});
});
var allMarkers = [];
for (var i = 0; i < arrLocation.length; i++) {
//final position for marker, could be updated if another marker already exists in same position
var latlng = new google.maps.LatLng(arrLocation[i].Latitude, arrLocation[i].Longitude);
var finalLatLng = latlng;
var comparelatlng = "(" + arrLocation[i].Latitude + "," + arrLocation[i].Longitude + ")";
var copyMarker = arrLocation[i];
var marker = new google.maps.Marker({
position: new google.maps.LatLng(arrLocation[i].Latitude, arrLocation[i].Longitude),
map: map,
title: 'Equine # ' + arrLocation[i].Id,
icon:"abc.png"
});
var markerInfo = "Reference # : <b>" + arrLocation[i].Id + "</b><br/>";
markerInfo = markerInfo + "Assessor : <b>" + arrLocation[i].AssessorDetail + "</b><br/>";
markerInfo = markerInfo + "Date : <b>" + arrLocation[i].AssessmentDate + "</b><br/>";
markerInfo = markerInfo + "Partner : <b>" + arrLocation[i].PartnerName + "</b>";(function (marker, i) {
bindInfoWindow(marker, map, new google.maps.InfoWindow(), markerInfo);
})(marker, i);
}
})();
});
function bindInfoWindow(marker, map, infowindow, html) {
google.maps.event.addListener(marker, 'click', function () {
infowindow.setContent(html);
infowindow.open(map, marker);
});
}
</script>
`
results[0].geometry.location is already a latLng object so you can just say:
center: results[0].geometry.location
Find the working fiddle here : http://jsfiddle.net/87z9K/
It is because of the worng "google.maps.LatLng" provided.
provide for a test the coords and it will work.
replace the line
center: new google.maps.LatLng(results[0].geometry.location),
with
center: new google.maps.LatLng(-34.397, 150.644)
get England coords
It wasn't exactly your issue, but closely related.
I found that I had to set the mapOptions with a valid centre, like so:
new google.maps.Map(mapCanvas, {
center: new google.maps.LatLng(-34.397, 150.644)
});
If I didn't enter map options, or if I did and it didn't have a valid center set, I'd get a blank map that didn't load tiles.
This can also occur if the height/width of the map is 0.
I tried to set map's MapTypeId and it helped as Anurag proposed:
map.setMapTypeId(google.maps.MapTypeId.TERRAIN);
I can see a general javascript issue with your code.
Your script might trying to embed the map in the page before the HTML is loaded.
Call the function like this (there are other ways).
<body onload="initialize()">

Map not displaying on url

today i'm trying to create a google map with some data, the thing is that i'm copying/pasting the code of google maps examples, but nothing is coming... i get a blank page.... Am i that crazy?
Can you please tell me what's going on?
I'm using chrome and firefox.. both blank.
<!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>Google Maps JavaScript API v3 Example: Polygon Arrays</title>
<link href="/maps/documentation/javascript/examples/default.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var map;
var infoWindow;
function initialize() {
var myLatLng = new google.maps.LatLng(24.886436490787712, -70.2685546875);
var myOptions = {
zoom: 5,
center: myLatLng,
mapTypeId: google.maps.MapTypeId.TERRAIN
};
var bermudaTriangle;
map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
var triangleCoords = [
new google.maps.LatLng(25.774252, -80.190262),
new google.maps.LatLng(18.466465, -66.118292),
new google.maps.LatLng(32.321384, -64.75737)
];
bermudaTriangle = new google.maps.Polygon({
paths: triangleCoords,
strokeColor: "#FF0000",
strokeOpacity: 0.8,
strokeWeight: 3,
fillColor: "#FF0000",
fillOpacity: 0.35
});
bermudaTriangle.setMap(map);
// Add a listener for the click event
google.maps.event.addListener(bermudaTriangle, 'click', showArrays);
infowindow = new google.maps.InfoWindow();
}
function showArrays(event) {
// Since this Polygon only has one path, we can call getPath()
// to return the MVCArray of LatLngs
var vertices = this.getPath();
var contentString = "<b>Bermuda Triangle Polygon</b><br />";
contentString += "Clicked Location: <br />" + event.latLng.lat() + "," +
event.latLng.lng() + "<br />";
// Iterate over the vertices.
for (var i =0; i < vertices.length; i++) {
var xy = vertices.getAt(i);
contentString += "<br />" + "Coordinate: " + i + "<br />" + xy.lat() +"," + xy.lng();
}
// Replace our Info Window's content and position
infowindow.setContent(contentString);
infowindow.setPosition(event.latLng);
infowindow.open(map);
}
</script>
</head>
<body onload="initialize()">
<div id="map_canvas"></div>
</body>
</html>
The problem is that you have copied the relative reference to Google's stylesheet, and that's where the size of map_canvas is defined.
If you set the size of that div explicitly, or use an absolute reference to the stylesheet, it will work (I just tried that).

Categories

Resources