How can I input a set of coordinates and have Google maps show a location. This is all to be done through javascript (ie: no user interface)
Any help is appreciated
Note: If you already have a latitude/longitude, see Alteveer’s answer.
You'll need to need to use a geolocation service to get the latitude/longitude. Google Maps has one built in:
http://code.google.com/apis/maps/documentation/javascript/services.html#Geocoding
Here's an example of how to use it:
<!-- Placeholder for the Google Map -->
<div id="map" style="height: 512px;">
<noscript>
<!-- http://code.google.com/apis/maps/documentation/staticmaps/ -->
<img src="http://maps.google.com/maps/api/staticmap?center=1%20infinite%20loop%20cupertino%20ca%2095014&zoom=16&size=512x512&maptype=roadmap&sensor=false" />
</noscript>
</div>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
// Define the address we want to map.
var address = "1 infinite loop cupertino ca 95014";
// Create a new Geocoder
var geocoder = new google.maps.Geocoder();
// Locate the address using the Geocoder.
geocoder.geocode( { "address": address }, function(results, status) {
// If the Geocoding was successful
if (status == google.maps.GeocoderStatus.OK) {
// Create a Google Map at the latitude/longitude returned by the Geocoder.
var myOptions = {
zoom: 16,
center: results[0].geometry.location,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map"), myOptions);
// Add a marker at the address.
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
} else {
try {
console.error("Geocode was not successful for the following reason: " + status);
} catch(e) {}
}
});
</script>
You should be able to initialize the map with latitude/longitude as follows: https://developers.google.com/maps/documentation/javascript/tutorial#MapOptions
Related
I am trying to create a google map. the latitude and the longitude are from the database so I had to put those in a textbox then get its value in the script. I tried doing so but it doesn't work will you help me with this one; here's my JavaScript:
function initMap() {
var lat = document.getElementById('lat');
var lang = document.getElementById('lang');
var uluru = {lat: lat, lng: lang };
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: uluru
});
var marker = new google.maps.Marker({
position: uluru,
map: map
});
}
Here's the html:
<input type="text" style="display: none" id="lat" value="7.8383054" />
<input type="text" style="display: none" id="lang" value="123.2966657" />
<div id="map" ">
</div>
JSfiddle
the "numbers" in the text fields are access using the .value property:
the lat/lng in a google.maps.LatLngLiteral must be numbers. (without the parseFloat the API throws these errors:
InvalidValueError: setCenter: not a LatLng or LatLngLiteral: in property lat: not a number
InvalidValueError: setPosition: not a LatLng or LatLngLiteral: in property lat: not a number
var lat = parseFloat(document.getElementById('lat').value);
var lang = parseFloat(document.getElementById('lang').value);
You need to actually call the initMap method (your fiddle isn't doing this)
updated fiddle
code snippet:
html,
body,
#map {
height: 100%;
width: 100%;
}
<script src="https://maps.googleapis.com/maps/api/js?callback=initMap" async defer></script>
<input type="text" id="lat" value="7.8383054" />
<input type="text" id="lang" value="123.2966657" />
<div id="map" ">
</div>
<script>
function initMap() {
var lat = parseFloat(document.getElementById('lat').value);
var lang = parseFloat(document.getElementById('lang').value);
var uluru = {lat: lat, lng: lang };
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: uluru
});
var marker = new google.maps.Marker({
position: uluru,
map: map
});
}
</script>
Try:
var lat = document.getElementById('lat').value;
var lang = document.getElementById('lang').value;
Not really sure where your problem lies aside from not actually using the value of the text inputs or calling the function that returns those values but perhaps something long these lines might help get you started. If you are needing the user to enter different lat/lng coordinates then you would also need an event handler assigned to listen for changes or a button to submit the new coordinates.
<?php
/*
*/
?>
<!doctype html>
<html>
<head>
<title>Google maps</title>
<script src='https://www.google.com/jsapi' charset='utf-8'></script>
<script src='https://maps.google.co.uk/maps/api/js?key=APIKEY' charset='utf-8'></script>
<script type='text/javascript' charset='utf-8'>
function initMap() {
var uluru = {
lat: document.getElementById('lat').value,
lng: document.getElementById('lang').value
};
var options={
zoom: 4,
center: uluru
};
var map = new google.maps.Map( document.getElementById('map'), options );
var marker = new google.maps.Marker({
position: uluru,
map: map
});
}
document.addEventListener( 'DOMContentLoaded', initMap, false );
</script>
<style type='text/css' charset='utf-8'></style>
</head>
<body>
<div id='map'></div>
<div>
<input type='text' id='lat' value='7.8383054' />
<input type='text' id='lang' value='123.2966657' />
</div>
</body>
</html>
call initMap() function in body tag. it will load the map, the most important thing do you have api key ? you also need ssl to use google maps. means your url must be https://yourdomain.com
body onload="initMap()"
I am trying to display a map, zoom into a zipcode, and then place Congressional District overlay onto map. The overlay is here: https://www.google.com/fusiontables/DataSource?snapid=S506424n-DY
I downloaded the KML link file, and saved it onto my local IIS server. However, the overlay never is drawn.
I also added the following mime types to my IIS Server:
.kml application/vnd.google-earth.kml+xml
.kmz application/vnd.google-earth.kmz
The kml file looks like this:
<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://www.opengis.net/kml/2.2">
<NetworkLink>
<name><![CDATA[2012 US Congressional Districts]]></name>
<Link>
<href>
https://www.google.com/fusiontables/exporttable?query=select+col5+from+1QlQxBF17RR-89NCYeBmw4kFzOT3mLENp60xXAJM&o=kmllink&g=col5</href>
</Link>
My HTML/javascript looks like:
<script src="http://maps.googleapis.com/maps/api/js" type="text/javascript"></script>
<script language="javascript">
var map;
var marker;
function showAddress() {
$("#divGoogleMap").css('display', '');
var mapProp = {
center: new google.maps.LatLng(51.508742, -0.120850),
zoom: 11,
mapTypeId: google.maps.MapTypeId.TERRAIN
};
map = new google.maps.Map(document.getElementById("divGoogleMap"), mapProp);
myListener = google.maps.event.addListener(map, 'click', function (event) {
placeMarker(event.latLng);
});
google.maps.event.addListener(map, 'drag', function (event) {
placeMarker(event.latLng);
});
var zipCode = $("#txtZip").val();
var geocoder = new google.maps.Geocoder();
geocoder.geocode({ 'address': zipCode }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
//Got result, center the map and put it out there
var pos = results[0].geometry.location;
saveLocation(pos);
map.setCenter(pos);
marker = new google.maps.Marker({
map: map,
draggable: true,
position: pos
});
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
var kmlUrl = '/DesktopModules/HelloWorld/2012_US_Congressional_Districts.kml';
var kmlOptions = {
suppressInfoWindows: true,
preserveViewport: false,
map: map
};
var kmlLayer = new google.maps.KmlLayer(kmlUrl, kmlOptions);
}
function placeMarker(location) {
if (marker) {
marker.setPosition(location);
} else {
marker = new google.maps.Marker({
position: location,
map: map,
draggable: true
});
google.maps.event.addListener(marker, "drag", function (mEvent) {
populateInputs(mEvent.latLng);
});
}
saveLocation(location);
}
function saveLocation(pos) {
$("#hfLatitude").val(pos.lat());
$("#hfLogitude").val(pos.lng());
}
</script>
<table cellpadding="2" cellspacing="2" border="0">
<tr>
<td>
<asp:TextBox ID="txtZip" ClientIDMode="Static" runat="server"></asp:TextBox>
</td>
<td>
<input type="button" id="btnSearch" value="Search" onclick="showAddress()" />
</td>
</tr>
</table>
<div id="divGoogleMap" style="width: 800px;height: 600px;display: none;"></div>
<asp:HiddenField ID="hfLatitude" ClientIDMode="Static" runat="server" />
<asp:HiddenField ID="hfLongitude" ClientIDMode="Static" runat="server" />
What am I doing wrong here?
For use in google maps th kml must be located in an accessible server e not in local.
This is form google doc.
Overview
The Google Maps API supports the KML and GeoRSS data formats for
displaying geographic information. These data formats are displayed on
a map using a KmlLayer object, whose constructor takes the URL of a
publicly accessible KML or GeoRSS file.
the constructor take the URL of a publicly accessible KML.
Then for yoour need you must place your kml in a publicly accessible server
I had forgotten that i had already had a similar experience some years ago and the solution was precisely to place the files kml on a server accessible from the Internet.
Details
I want to convert address to coordinates
I want to use that coordinate to populate a map view
I know my $coordinate variable = 42.6358311,-71.3290596
I got that by simply running alert( coordinates );
What I have now
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var geocoder = new google.maps.Geocoder();
var address = "410 walker street Lowell MA 01851";
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var latitude = results[0].geometry.location.lat();
var longitude = results[0].geometry.location.lng();
var coordinates = [latitude , longitude];
alert( coordinates );
}
});
</script>
Note : 410 walker street Lowell MA 01851 -> 42.6358311,-71.3290596
<iframe
width="200"
height="200"
frameborder="0" style="border:0"
src="https://www.google.com/maps/embed/v1/view?key=**********
¢er= 42.6358311,-71.3290596
&zoom=18
&maptype=satellite"
>
</iframe>
If I run this code I will get this result
So far everything work, you might wondering, since everything work why am I asking ?
Here is my question, rather than inputing the latitude and the longitude manually in ¢er= 42.6358311,-71.3290596 I was wondering, if I can print out whatever stored inside my $coordinate variable.
Can someone please help me how to do that ?
I just want to print out my $coordinate variable as part of my HTML attribute.
See the documentation
"Highlight a place or an address" gives me this result:
<iframe width="600" height="450" frameborder="0" style="border:0"
src="https://www.google.com/maps/embed/v1/place?q=410+walker+street+Lowell+MA+01851
&key=..."></iframe>
Try this code snippet, may be this help you...
var geocoder = new google.maps.Geocoder();
var address = "410 walker street Lowell MA 01851";
geocoder.geocode({
'address': address
}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var latitude = results[0].geometry.location.lat();
var longitude = results[0].geometry.location.lng();
var coordinates = [latitude , longitude];
var mapOptions = {
zoom: 18,
center: new google.maps.LatLng(latitude, longitude),
mapTypeId: google.maps.MapTypeId.SATELLITE
};
map = new google.maps.Map(document.getElementById('map_canvas'),
mapOptions);
document.getElementById('myText').value = coordinates;
}
});
<script src="http://maps.googleapis.com/maps/api/js?libraries=places&sensor=false"></script>
<div id="map_canvas" style="width:500px; height:200px"></div>
<br />
<p>Print out your coordinate : </p><input type="text" id="myText" >
do you want to print out like this ?
Please correct me if I'm wrong..
I'm using Ruby on Rails and don't have much knowledge in JavaScript(of course, my overall coding is so poor). I customized Google Maps API and wanted to make infowindow. However when I made my infowindow, 'sometimes' dropdown popped up in desktop(not in cell phone).
I think it's not only the Google Maps problem. I assumed that it can be any HTML, CSS related problem but no idea afterall..... It's very strange because dropdown only pops up when the restaurant's name is some kinds(two words or name with some number, but I can't recognize what is the exact cause and difference..)
# my_javascript.js
function googleMap() {
var geocoder = new google.maps.Geocoder();
var restAddr = document.getElementById('address').value;
var restName = document.getElementById("name").value;
geocoder.geocode( { 'address': restAddr}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var restLatLng = results[0].geometry.location
var mapOptions = {
zoom: 13,
center: restLatLng
};
var map = new google.maps.Map(document.getElementById("map-canvas"),mapOptions);
var marker = new google.maps.Marker({
map: map,
position: restLatLng
});
var infoWindow = new google.maps.InfoWindow({
//maxWidth: 100, it didn't work
content: restName // **this part is the problem. When the restName is like "new york", "house 2"(some with one-digit(?)-number). but not when the restName is "new york stree" kind. **
});
infoWindow.open(map, marker);
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
window.onload = googleMap
and this is my view file.
# app/views/home/page.html.erb
<%= #rest.addr %>
<p>changed</p>
<input type="hidden" id="address" value="<%= #rest.addr %>">
<input type="hidden" id="name" value="<%= #rest.name %>">
<div id="map-canvas"></div>
Can anyone help me with some suggestions? Any comments will be very helpful to me and make me learn more about programming. Thanks!!
You have to get the infowindow content in da DIV and style the div with css.
In your case do '<div class="scrollFix">'+restName+'</div>' und set the div properties to:
.scrollFix {
line-height: 1.35;
overflow: hidden;
white-space: nowrap;
}
here is an working example :
http://jsfiddle.net/veaz/7Zm8w/
I am in a situation where I need to draw Google map using api v3 with multiple locations. These location can be static address string like "New Delhi, India" or 110005, but they will be several in numbers - can be comma separated or an array - i dont know exactly how they need to be put in the code. But simply i want to draw gmap with multiple locations, so a given map will have 9 or 10 location at once. How to do that? Can you please give me any working code on jsfiddle. For now my code to draw a gmap with only a single location (address only and not zip code) is given below -
JavaScript -
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script type="text/javascript">
var geocoder;
var map;
var marker;
function initialize()
{
geocoder = new google.maps.Geocoder();
var myOptions = {
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
}
function codeAddress()
{
//var address = "Talwara Township, Punjab";
var address = document.getElementById("txtaddress").value;
geocoder.geocode({'address': address}, function(results, status){
if(status == google.maps.GeocoderStatus.OK)
{
map.setCenter(results[0].geometry.location);
marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
var infowindow = new google.maps.InfoWindow({
content: "New Delhi, India"
});
infowindow.open(map, marker);
// Click the marker to Zoom to 9
google.maps.event.addListener(marker, 'click', function() {
map.setZoom(9);
map.setCenter(marker.getPosition());
});
}
});
}
</script>
HTML -
<body onLoad="initialize();codeAddress();">
<form method="get" action="">
<input type="text" id="txtaddress" name="txtaddress" size="30" value="New Delhi, India" />
<input type="submit" name="btnsubmit" value="Generate Map" />
</form>
<br /><br />
<div id="map_canvas" style="width:500px; height:380px; border:1px solid #AFAFAF;"></div>
</body>
What you are asking is Batch GeoCoding. The process of changing multiple addresses into a Geographical location is referred to as Batch GeoCoding.
Google Maps API is not directly supporting BatchGeocoding.
By using Google Maps API , We do geocode a single address at a time.
To acheive BatchGeoCoding, We need to iterate a list of Address.(Not too difficult I think)
For best Practice : GeoCode Example
BatchGeocode Reference :
The following are online batch Geocoding sites. Have it for reference.
Ref 1 , Ref 2
Working Demo
The Working demo is just a Proof of the Concept. It has to be refined in many ways. Please have a look at the reference to produce a better code.