i am new to google maps,
and i would like to integrate it into my website ( Yellow pages kind of site ).
i currently have the following code:
<!DOCTYPE html>
<html>
<head>
<title></title>
<script type="text/javascript" src="jquery-1.6.2.min.js"></script>
<script src="http://maps.googleapis.com/maps/api/js?sensor=false" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
var latlng = new google.maps.LatLng(-34.397, 150.644);
var myOptions = { zoom: 8, center: latlng, mapTypeId: google.maps.MapTypeId.ROADMAP };
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
});
</script>
</head>
<body>
<div id="map_canvas" style="width: 500px; height: 300px; position: relative; background-color: rgb(229, 227, 223);"></div>
</body>
</html>
This code does work, and showing me the map for the specific Lat/Long
but, i want to be able to specifiy an address and not lat/long params,
since i do have the addresses of the companies in the phonebook, but do not have the lat/long values.
i tried searching for this, but i only found something similar on the V2 version, which was deprecated.
What you are looking for is Geocode feature in google service; first give an address to get a LatLng, then call setCenter to pan the map to the specific location. Google's API wrapped it very good and you can see how it works through this example:
var geocoder;
var map;
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(-34.397, 150.644);
var mapOptions = {
zoom: 8,
center: latlng
}
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
}
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);
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
You can use the google geocoder: http://code.google.com/apis/maps/documentation/geocoding/ Be careful - you can be out of quota and so the request to the geocoder will failed
Use of the Google Geocoding API is subject to a query limit of 2,500 geolocation requests per day.
If you are okay with an iframe, you can skip the geocoding hassle and use the Google Maps Embed API:
The Google Maps Embed API is free to use (with no quotas or request
limits), however you must register for a free API key to embed a map
on your site.
For example you would embed this into your page (replacing the ellipsis with your own personal Google API key):
<iframe width="600" height="450" frameborder="0" style="border:0"
src="https://www.google.com/maps/embed/v1/place?
q=301+Park+Avenue,+NY,+United+States&key=..."></iframe>
Obviously the usefulness of this will depend on your use case but I like this as a quick and dirty solution.
There is a plugin for jQuery that makes it, it's name is gMap3, and you can see it in action here:
http://gmap3.net/examples/address-lookup.html
and here
http://jsfiddle.net/gzF6w/1/
gmap3 doesn't actually do it for you, as suggested by another answer: it just gives you an API to abstract-away the geocoding part of the process.
The answer is: Google doesn't actually allow you to do that anymore. At least not in V3, and since that's been around for more than a year...
You could actually send addresses for driving directions, but their API has made it illegal to send an address for a normal (embedded, API-based) map of any sort. The daily quota on geocoding is their play at "still allowing" addresses while in reality completely disallowing them for any real website.
You can link to a map with an address, though I cannot find this in Google's docs either:
http://maps.google.com/maps?f=d&saddr=&daddr=this is my address, city state
Maybe I just have a problem with this because they don't provide any clear, easy documentation - I have to come to StackOverflow to get the answers I'm looking for. Ie. they vaguely mention you need an API key to bypass the anonymous limits, but do not link either to what those limits are or how to use their API without a key. Which is what I want to do for skunkworks or proof-of-concept development. Instead Google wants to push their Maps for Businesses, etc., instead of providing actual information.
Related
I have an ASP.NET Core 2.2 website that creates a map from an address using the google geocoding api and map javascript api. It works in Visual Studio 2017, but when I publish it to Azure, it doesn't work anymore. The map doesn't appear. The developer console shows no errors.
I use the Geocoding API to generate a latlong, from the street address. I added a debug statement to confirm that I am successfully talking to the api, and it does get lat long back.
The website is http://americanhorseproperties.com
<div id="map">
</div>
<a asp-page="./Index">Back to Gallery</a>
<input type="hidden" id="address" value="#Model.house.address
#Model.house.city" />
<script>
// Initialize and add the map
function initMap() {
var geocoder = new google.maps.Geocoder();
//gets address from the address hidden input element in body
var address = document.getElementById('address').value;
//geocodes address and gets latlong
geocoder.geocode({ 'address': address }, function (results, status) {
if (status == 'OK') {
console.log('location: Longitude: ',
results[0].geometry.location.lng());
console.log('location: Latitude: ',
results[0].geometry.location.lat());
var map = new google.maps.Map(document.getElementById('map'), { zoom: 14,
center: results[0].geometry.location });
var marker = new google.maps.Marker({ map: map, position:
results[0].geometry.location }); //sets marker at new lat long
} else {
alert('Geocode was not successful for the following reason: ' +
status);
}
});
}
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?
key=KEY_REMOVED&callback=initMap">
</script>
It seems you need to set "height" property for <div id="map">
CSS Problem.
The Google Maps API automatically adds the CSS properties "position: relative; overflow: hidden;" to the div that is used for displaying the map. When I manually remove any of these two properties in the developer console of the browser, the map becomes visible.
Make sure the div has a size that the map can fill.
Morning all.
I'm am currently using the below code to load my Google Map's API V3 at a specific long-lat, it's for a client and I'm wondering if I can load an infoWindow similar to the one the pops up on Google Maps with the business information, review stars etc.
<script type="text/javascript">
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(lat-long),
disableDefaultUI: true,
zoom: 16,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("location"),
mapOptions);
var point = new google.maps.LatLng(lat-long);
var marker = new google.maps.Marker({
position:point,
map: map,
});
}
</script>
Is this done in a different API? If so could anyone point me to some helpful information?
Sounds like you might be looking for the Places API/Library:
https://developers.google.com/maps/documentation/javascript/places#place_details_responses
Not sure if it has everything you find on Google Maps.
I'm looking to simply add a google map using google maps api to one of my pages in WordPress. Is there a simple way of simply copy and pasting the "Hello, World" google maps code somewhere to have the map displayed on a page?
thanks
Yes, there's no need for a plugin for something like this. First of all you would include the Google maps script in header.php or you could enqueue it;
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=true"></script>
Then I normally add the following in header.php - this adds conditional code to the tag for the page containing the map only (in this case page 374);
<body <?php if (is_page(374)) { echo 'onload="initialize()" onunload="GUnload()"'; } ?>>
And then I would create a custom template for the contact page (as that's the page the map is normally on) and in the template for that page include something like the following. Yes, it's probably a bit long for a code sample but I'm just giving you a real example which contains an animated marker which can be clicked on to show your client's address. You could change the inline dimensions to suit your design, and you can also offset the map so the marker isn't right smack in the middle of it.
<div id="contact-content">
<script type="text/javascript">
function initialize() {
var leeds = new google.maps.LatLng(53.80583, -1.548903);
var firstLatlng = new google.maps.LatLng(53.80583, -1.548903);
var firstOptions = {
zoom: 16,
center: firstLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_leeds"), firstOptions);
firstmarker = new google.maps.Marker({
map:map,
draggable:false,
animation: google.maps.Animation.DROP,
title: 'Your Client',
position: leeds
});
var contentString1 = '<p>The Address<br />Of your client<br />in<br />here</p>';
var infowindow1 = new google.maps.InfoWindow({
content: contentString1
});
google.maps.event.addListener(firstmarker, 'click', function() {
infowindow1.open(map,firstmarker);
});
}
</script>
<div class="map">
<div id="map_leeds" style="width: 600px; height: 600px"></div>
</div>
</div>
If anyone else does it a different, better way then I'd be keen to see it, but I've used this on loads of sites and it works really well.
I have a google map embedded in a site that loads a kml file at https://www.getstable.org/who-can-help/therapist-map-kml using KmlLayer. Sometimes the map doesn't load up, I presume because google maps has a strict timeout, and often some of the pins on the map aren't clickable but some are with no clear reason why. Does anyone know what the timeout limit is on kmlLayer and how to increase it? Also is there any reason why sometimes some of the pins aren't clickable (ie no InfoWindow appears when you click a pin and the cursor doesn't change to a hand)?
Here's the code that shows it (some of the fields are templated):
<div id="map_canvas" style="width: 856px;height: 540px;">Loading...</div>
<script type="text/javascript" src="{protocol}://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var the_map = {
options : {
zoom:{embed:zoom_level},
center:new google.maps.LatLng({embed:latitude},{embed:longitude}),
mapTypeId: google.maps.MapTypeId.ROADMAP
},
geocoder : null,
map : null,
init : function() {
this.geocoder = new google.maps.Geocoder();
$('#map_canvas').delegate('a', 'click', function(event) {
window.location.href=$(this).attr('href');
return false;
});
},
load_map : function() {
this.map = new google.maps.Map(document.getElementById("map_canvas"), this.options);
query = encodeURI('{site_url}{embed:map_url}');
var ctaLayer = new google.maps.KmlLayer(query,{
preserveViewport:true
});
ctaLayer.setMap(this.map);
}
}
$(document).ready(function() {
the_map.init();
the_map.load_map();
});
</script>
The Google Servers have an unspecified timeout, but testing shows it to be 3-5 seconds. This timeout is not something you can affect. The solution is to make your server respond faster. This issue almost always comes down to a file that is too big (yours isn't) or from dynamically generating the KML. You need to optimize this and that may mean finding a way to create a static KML file.
Features that are not clickable are almost certainly a problem with your KML. You can validate your KML to check for this:
Feed Validator
KML Validator
You can also test your KML by loading it at maps.google.com.
How to use own map database to display map on a website and use that map to find route and do other stuff ?
You should try the Google Maps API. http://code.google.com/apis/maps/index.html
You can store locations or routes in your database and use the Maps API to display them. Not sure if this is what you're looking for, but I've found their API really easy to use.
That is an absolutely massive task, I'm not sure I understand your question correctly... You've tagged this with Javascript, Web-development and map - so presumably you want to know how to implement a front-end that renders a map to a web page, and then performs custom pathfinding and other logic. Surely I'm misunderstanding you! :D
The O'rielly RESTful Web Services book uses a map service as its operative example throughout the book, so you may find it useful, at least for the design of your service front end. It doesn't delve into the implementation very deeply, particularly the actual mechanics of map image generation, as it is primarily concerned with the design of the service interface from an HTTP perspective. It also doesn't treat very much with the client-side logic that would be involved in dragging, zooming and the like.
You have two options in order to calculate routes depending on your database.
If your database has clean and accurate address names then you can easily use the google maps API that can be found here: https://developers.google.com/maps/documentation/directions/.
Bare in mind that you can only execute 2500 requests per day with the free version.
On the other hand if you have a network defined on your db (have the roads in a nodes and arcs manner) then you can implement Dijsktra's algorithm.
Have a look here: http://www.vogella.com/articles/JavaAlgorithmsDijkstra/article.html
Because of the fact that the network should be loaded from the database in order to calculate the best route I suggest the singleton pattern.
An OpenSource way to do this, which I would recommend in most cases, is using GeoServer and OpenLayers.
GeoServer can read gegraphic data from all the major databases and be used as host for the widely used standard GeographicgWebServices WMS and WFS.
OpenLayers is a JavaScript API to show your map on the webpage.
I recently implemented something like this. I realize it is an old question but Google has the javascript api v3 out for Google Maps and it works great.
https://developers.google.com/maps/articles/phpsqlajax_v3
This page helped me implement the entire system. Works great. You can also use php to update and edit the entries on the map.
You need xml pages and others but here is the map html page just to give you an idea of the javascript it entails.
<!DOCTYPE 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>PHP/MySQL & Google Maps Example</title>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
//<![CDATA[
var customIcons = {
restaurant: {
icon: 'http://labs.google.com/ridefinder/images/mm_20_blue.png',
shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
},
bar: {
icon: 'http://labs.google.com/ridefinder/images/mm_20_red.png',
shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
}
};
function load() {
var map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(47.6145, -122.3418),
zoom: 13,
mapTypeId: 'roadmap'
});
var infoWindow = new google.maps.InfoWindow;
// Change this depending on the name of your PHP file
downloadUrl("phpsqlajax_genxml.php", function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var name = markers[i].getAttribute("name");
var address = markers[i].getAttribute("address");
var type = markers[i].getAttribute("type");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var html = "<b>" + name + "</b> <br/>" + address;
var icon = customIcons[type] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
icon: icon.icon,
shadow: icon.shadow
});
bindInfoWindow(marker, map, infoWindow, html);
}
});
}
function bindInfoWindow(marker, map, infoWindow, html) {
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(html);
infoWindow.open(map, marker);
});
}
function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function doNothing() {}
//]]>
</script>
</head>
<body onload="load()">
<div id="map" style="width: 500px; height: 300px"></div>
</body>
</html>