The Google Maps web application geocodes and outlines regional areas in a very nice fashion. Is this possible through the Google Maps JavaScript API? An example of the website:
https://maps.google.se/maps?q=sk%C3%A5ne&hl=sv&ie=UTF8&ll=57.1422,13.337402&spn=5.468408,16.907959&sll=39.290385,-76.612189&sspn=0.243658,0.528374&hnear=Sk%C3%A5ne+l%C3%A4n&t=m&z=7
This is the county of Skåne in Sweden. The Google Maps web application outlines it in red and shades it pink. I want to geocode and display regions like this with the Google Maps JavaScript API. How?
As far as I know the boundaries feature is not provided from the Google Map API v3 yet.
You need to know the boundaries in order to shape a polygon. The information which is returned by the Geocoder given the address in not enough to shape the boundaries. You may see the returned info here.
The Stockholm boundaries are: '17.73966,59.66395|17.75651,59.61827|17.81771,59.58645|17.84347,59.53069|17.78465,59.49340|17.78277,59.38916|17.83277,59.36500|17.93215,59.33652|18.00736,59.34496|18.09139,59.33444|18.05722,59.39139|18.12000,59.45388|18.19508,59.45012|18.16562,59.41083|18.32826,59.39795|18.28659,59.41228|18.25945,59.44638|18.31722,59.47361|18.37333,59.46694|18.66638,59.59138|18.69979,59.64409|18.74555,59.68916|18.84139,59.71249|18.98569,59.71666|19.03222,59.71999|19.07965,59.76743|18.93472,59.78361|18.86472,59.79804|18.96922,59.86561|19.06545,59.83250|19.07056,59.88972|19.00722,59.91277|18.92972,59.92472|18.89000,59.95805|18.81722,60.07548|18.77666,60.11084|18.71139,60.12806|18.63277,60.14500|18.50743,60.15265|18.44805,59.99249|18.37334,59.86500|18.29055,59.83527|18.15472,59.79556|18.08111,59.74014|17.96055,59.70472|17.89694,59.68916|17.73966,59.66395'
In conclusion the hard part is to find the boundaries for the cities you want to get drawn on your map. I'm not sure whether there is a free service which provides these boundaries. Check this Stackoverflow question to get more information about sites which provide boundaries.
In the below example when you click the Draw Stockholm button then the Stockholm is drawn on the map.
<html>
<head>
<head>
<title>Area calculator - Outline a property on a google map and find its area</title>
<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=false&language=en">
</script>
<script type="text/javascript">
var map,
geocoder,
addressMarker,
mapCenter = new google.maps.LatLng(59.3426606750, 18.0736160278);
function initialize() {
map = new google.maps.Map(document.getElementById('map_canvas'), {
zoom: 7,
center: mapCenter,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
geocoder = new google.maps.Geocoder();
}
function showAddress() {
var address = $('#to').val();
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({
map: map,
position: results[0].geometry.location
});
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
function drawPolygon() {
// stockholm boundaries
var boundaries = '17.73966,59.66395|17.75651,59.61827|17.81771,59.58645|17.84347,59.53069|17.78465,59.49340|17.78277,59.38916|17.83277,59.36500|17.93215,59.33652|18.00736,59.34496|18.09139,59.33444|18.05722,59.39139|18.12000,59.45388|18.19508,59.45012|18.16562,59.41083|18.32826,59.39795|18.28659,59.41228|18.25945,59.44638|18.31722,59.47361|18.37333,59.46694|18.66638,59.59138|18.69979,59.64409|18.74555,59.68916|18.84139,59.71249|18.98569,59.71666|19.03222,59.71999|19.07965,59.76743|18.93472,59.78361|18.86472,59.79804|18.96922,59.86561|19.06545,59.83250|19.07056,59.88972|19.00722,59.91277|18.92972,59.92472|18.89000,59.95805|18.81722,60.07548|18.77666,60.11084|18.71139,60.12806|18.63277,60.14500|18.50743,60.15265|18.44805,59.99249|18.37334,59.86500|18.29055,59.83527|18.15472,59.79556|18.08111,59.74014|17.96055,59.70472|17.89694,59.68916|17.73966,59.66395';
var latLngArray = boundaries.split('|');
var points = [];
for (var i = 0; i < latLngArray.length; i++) {
pos = latLngArray[i].split(',');
points.push(new google.maps.LatLng(parseFloat(pos[1]), parseFloat(pos[0])));
}
var shape = new google.maps.Polygon({
paths: points,
strokeColor: '#ff0000',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#ff0000',
fillOpacity: 0.35
});
shape.setMap(map);
}
$(document).ready(function () {
initialize();
});
$(document).on('click', '.show-address', function (e) {
e.preventDefault();
showAddress();
});
$(document).on('click', '.draw-address', function (e) {
e.preventDefault();
drawPolygon();
});
</script>
</head>
<body>
<div id="basic-map">
<div id="map_canvas" style="height:150px;"></div>
<label for="to">Address</label>
<input type="text" id="to" value="Stockholm, Sweden" />
Show Address
Draw Stockholm
</div>
</body>
</html>
I hope this helps.
Related
Is there are way to retrieve a map from Google using the API so that it displays a list of local churches with churches with markers?
I have the basic syntax, and I have a basic API account setup, but I am not how/if I can use the type field.
var mapOptions = {
center: new google.maps.LatLng("-33.8670522", "151.1957362"),
zoom: 11,
scrollwheel: false,
streetViewControl: false,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("googlemaps"), mapOptions);
Yes, you can do this, using Google Places API.
I'll use JavaScript API, since you seem to have a map being built with such API.
As said in documentation:
The Places service is a self-contained library, separate from the main Maps API JavaScript code. To use the functionality contained within this library, you must first load it using the libraries parameter in the Maps API bootstrap URL:
<script src="https://maps.googleapis.com/maps/api/js?libraries=places"></script>
After this, using JavaScript Places API you can request places by type and a radius (in meters). The maximum allowed radius is 50.000 meters.
Here a piece of code that demonstrate this:
var request = {
location: sydney,
radius: 5000,
types: ['church']
};
var service = new gm.places.PlacesService(map);
service.nearbySearch(request, handlePlaceResponse);
Obs.: In this example, handlePlaceResponse is a callback to handle the response and create the markers. See in the complete example how it works.
This will request by churches in a 5km radius from Sydney point (lat: -33.8670522, lng: 151.1957362).
To overlay markers you'll need handle the response. In the example I used only name to put as content of InfoWindow. You can see details about the response here: Place Details Responses
So, a function to create markers look like this:
/**
* Creates marker with place information from response
*/
function createMarker(place) {
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location
});
var infowindow = new google.maps.InfoWindow();
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(place.name);
infowindow.open(map, this);
});
}
Also, if you need, for types supported in place search, see this link: Place Type
Here an example using as point the used by you and 5000 meters for radius:
<html>
<head>
<title>Google Maps - Places Sample</title>
<style>
body {
margin: 0;
}
#map {
height: 600px;
width: 100%;
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?libraries=places"></script>
<script>
var gm = google.maps;
var map;
var bounds;
var service;
var infowindow;
var sydney = new gm.LatLng(-33.8670522, 151.1957362);
function initialize() {
var options = {
zoom: 15,
center: sydney,
mapTypeId: gm.MapTypeId.ROADMAP,
streetViewControl: false,
scrollwheel: false
};
map = new gm.Map(document.getElementById("map"), options);
var request = {
location: sydney,
radius: 5000,
types: ['church']
};
bounds = new gm.LatLngBounds();
infowindow = new gm.InfoWindow();
service = new gm.places.PlacesService(map);
service.nearbySearch(request, handlePlaceResponse);
}
/**
* Handle place response and call #createMarker to creat marker for every place returned
*/
function handlePlaceResponse(results, status) {
if (status == gm.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
}
}
map.fitBounds(bounds);
map.setCenter(bounds.getCenter());
}
/**
* Creates marker with place information from response
*/
function createMarker(place) {
var location = place.geometry.location;
var marker = new gm.Marker({
map: map,
position: location
});
bounds.extend(location);
gm.event.addListener(marker, 'click', function() {
infowindow.setContent(place.name);
infowindow.open(map, this);
});
}
gm.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map"></div>
</body>
</html>
I currently enabled user to put the address into text-boxes and display the address on Google map, but I want to do the opposite now and get nearest matching address to the text-boxes (which are on a separate region, same page) from a draggable marker. I heard that I should use JSON with PHP or PL/JSON to get the data from the map to the text-boxes. However, I do not have any knowledge about JSON and I think Google map API provide this sort of geocoding methods inside the JavaScript. I am not sure how to fully apply it, and if it is possible to get both methods in one page (or maybe I should use some procedure with JavaScript and call it on the page, not sure). Here is my code so far in the HTML Header of the page:
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script type="text/javascript">
var uniLatLng = new google.maps.LatLng (51.887496, -2.088788);
var geocoder = new google.maps.Geocoder();
var map;
function geocodePosition(pos) {
geocoder.geocode({
latLng: pos
},
function(responses) {
if (responses && responses.length > 0) {
updateMarkerAddress(responses[0].formatted_address);
}
else {
updateMarkerAddress('Cannot determine address at this location.');
}
});
}
function updateMarkerStatus(str) {
document.getElementById('P15_ADDRESS').value;
}
function initialize() {
geocoder = new google.maps.Geocoder();
var mapOptions = {
zoom: 16,
center: uniLatLng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
};
var marker = new google.maps.Marker({
map: map,
animation: google.maps.Animation.DROP,
flat: false,
position: new google.maps.LatLng(59.327383, 18.06747)
})
function map_canvas() {
var address = "&P15_ADDRESS.";
geocoder.geocode( { 'address': address, 'region': "GB"}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
draggable: true,
animation: google.maps.Animation.DROP,
flat: false,
position: results[0].geometry.location
});
}
else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
</script>
Page HTML Body Attribute - onload="initialize(), map_canvas()"
Any suggestions how can I achieve this?
I think this example does what you want on the Reverse Geocoding part. https://developers.google.com/maps/documentation/javascript/examples/geocoding-reverse
the only thing you need to add to this is a draggable marker with a listener for on dragged, which would update the position and call the same methods as it is in the Reverse Geocode button.
i am trying to implement google map in chrome, however the geolocation doesn't seems to be working i also changed the setting to 'allow all site to track'
i have taken these code from a tutorial online, and hence i couldn't find a way to make it work
<head>
<title>Map</title>
<!-- Google Maps and Places API -->
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?libraries=places&sensor=false"></script>
<!-- jQuery -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
function initGeolocation(){
if( navigator.geolocation ){
// Call getCurrentPosition with success and failure callbacks
navigator.geolocation.getCurrentPosition( success, fail );
}else{
alert("Sorry, your browser does not support geolocation services.");
}
}
var map;
function success(position){
// Define the coordinates as a Google Maps LatLng Object
var coords = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
// Prepare the map options
var mapOptions = {
zoom: 14,
center: coords,
mapTypeControl: false,
navigationControlOptions: {style: google.maps.NavigationControlStyle.SMALL},
mapTypeId: google.maps.MapTypeId.ROADMAP
};
// Create the map, and place it in the map_canvas div
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
//search for schools within 1500 metres of our current location, and as a marker use school.png
//placesRequest('Schools',coords,1500,['school']);
// Place the initial marker
var marker = new google.maps.Marker({
position: coords,
map: map,
title: "Your current location!"
});
}
function fail(){
// Could not obtain location
}
//Request places from Google
function placesRequest(title,latlng,radius,types,icon){
//Parameters for our places request
var request = {
location: latlng,
radius: radius,
types: types
};
//Make the service call to google
var callPlaces = new google.maps.places.PlacesService(map);
callPlaces.search(request, function(results,status){
//trace what Google gives us back
$.each(results, function(i,place){
var placeLoc = place.geometry.location;
var thisplace = new google.maps.Marker({
map: map,
position: place.geometry.location,
icon: icon,
title: place.name
});
})
});
}
</script>
initGeolocation() is not fired anywhere.
The div with id map_canvas is missing and you don't call initGeolocation function anywhere in your code .
Check here , everything works ok
We use Google Map Api V3 to load google map in HTML container. We have a location search form. On submit, we will get the available locations and set markers in map. Once markers are loaded, on click on each marker we need to show Title, address details and design like what we have in google map. (In google maps - When clicking on red marker, we can see the more info overlay box with additional details like Stars, Directions, Search nearby, Save to Map, More..)
Do we have built in api function to load the overlay box like above. Or we don't have the function to load the details like what we have in google map currently.
When i searched in google and map docs, i can see options to show overlay window and write content inside the box. But i didn't see options to load the content as required.
I have pasted the code below for reference.
var map = null;
gmap_ready = function (){
var myLatlng = new google.maps.LatLng(43.834527,-103.564457);
var myOptions = {
zoom: 3,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
}
function fnLoadMarkers(){
var locations = [
['S Dakota', 43.834527,-103.564457, 1],
['Texas', 31.428663,-99.418947, 2],
['California', 36.668419,-120.249025, 3],
['Newyork', 43.197167,-76.743166, 4],
['Missouri', 38.410558,-92.73926, 5]
];
setMarkers(map,locations);
}
function setMarkers(map, locations) {
var image = 'images/marker.gif';
for (var i = 0; i < locations.length; i++) {
var currLocation = locations[i];
var latLng = new google.maps.LatLng(currLocation[1], currLocation[2]);
var marker = new google.maps.Marker({
position: latLng,
map: map,
icon: image,
title: currLocation[0],
zIndex: currLocation[3]
});
google.maps.event.addListener(marker, 'click', function() {
var latitude = this.position.lat();
var longitude = this.position.lng();
window.open("http://maps.google.com/maps?f=q&source=s_q&hl=en&geocode=&q="+latitude+","+longitude+"&sll="+latitude+","+longitude+"&sspn=0.172749,0.4422&ie=UTF8&ll="+latitude+","+longitude+"&spn=0.162818,0.4422&z=11&iwloc=A");
});
}
}
If there is any hint on how to achieve these results, it will be helpful. Also, please guide, whether it is possible through Google API V3.
Thanks in Advance,
Regards
Srinivasan.C
I don't understand why are you opening a new window to Google Maps from a Google Maps API marker?
You cannot add info window on Google Maps via URL.
This is how I do it.
<!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"/>
<link href="http://code.google.com/apis/maps/documentation/javascript/examples/default.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
// Initiate map
function initialize(data) {
// Make position for center map
var myLatLng = new google.maps.LatLng(data.lng, data.lat);
// Map options
var myOptions = {
zoom: 10,
center: myLatLng,
mapTypeId: google.maps.MapTypeId.HYBRID
};
// Initiate map
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
// Info window element
infowindow = new google.maps.InfoWindow();
// Set pin
setPin(data);
}
// Show position
function setPin(data) {
var pinLatLng = new google.maps.LatLng(data.lng, data.lat);
var pinMarker = new google.maps.Marker({
position: pinLatLng,
map: map,
data: data
});
// Listen for click event
google.maps.event.addListener(pinMarker, 'click', function() {
map.setCenter(new google.maps.LatLng(pinMarker.position.lat(), pinMarker.position.lng()));
map.setZoom(18);
onItemClick(event, pinMarker);
});
}
// Info window trigger function
function onItemClick(event, pin) {
// Create content
var contentString = pin.data.text + "<br /><br /><hr />Coordinate: " + pin.data.lng +"," + pin.data.lat;
// Replace our Info Window's content and position
infowindow.setContent(contentString);
infowindow.setPosition(pin.position);
infowindow.open(map)
}
</script>
</head>
<body onload="initialize({lat:-3.19332,lng:55.952366,text:'<h2>Edinburgh</h2><i>Nice city!</i>'})">
<div id="map_canvas">
</div>
</body>
</html>
I'm using Google Maps api v. 3 in my website. What I want to implement is the following flow:
User is presented a form where he enters an address (of some kind - city, street, etc).
After the form is filled, a map is presented to him, showing him the map centered to the address he entered. Then he can enter a keyword to search against google places in the area of the map.
What I'm stopped at is the translation of the address to map. As I understand the v3 API, I should initialize the map with LatLng center position - but having a city name or so I can't do it just yet. I need some kind of translation between the textual address and coordinates - it's what Google Maps are doing when I search for "Beverly Hills" for example. Some kind of reverse, I guess? How should I do it in the javascript API?
Or is there an option to include a search bar inside the v3 embedded map?
You need to use geocode something like below
Copied from http://code.google.com/apis/maps/documentation/javascript/geocoding.html
var geocoder;
var map;
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(-34.397, 150.644);
var myOptions = {
zoom: 8,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
}
function codeAddress() {
var address = document.getElementById("address").value;
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({
map: map,
position: results[0].geometry.location
});
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
And then you will need to call codeAddress() function on your button click
You can use the Google Maps v3 Geocoding API for translating an address to a lat/lon pair. After this you can use that data to initialize the map.