I'm trying to integrate the geocoder of Google Maps into my ol-map. There are a lot of similar questions asked. I tried out this: http://dev.openlayers.org/sandbox/topp/almanac/examples/geocoder.html example but it doesn't work. Looking through: How to use Google Maps geocoding with Openlayers? also didn't help me.
(As I'm new here I cannot comment on peoples answers so I thought it might be OK to open a new question - tell me if I'm wrong) See code below for my attempt. Do you have any tips or know any working example?
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Google styled in OL mit kml</title>
<link rel="stylesheet" href="OpenLayers-2.12/theme/default/style.css" type="text/css">
<link rel="stylesheet" href="OpenLayers-2.12/theme/default/google.css" type="text/css">
<script src="http://maps.google.com/maps/api/js?v=3&sensor=false"></script>
<script src="OpenLayers-2.12/lib/OpenLayers.js"></script>
<style type="text/css">
html, body {
height: 100%;}
#map {
width: 100%;
height: 80%;
border: 1px solid black;}
.olPopup p { margin:0px; font-size: .9em;}
.olPopup h2 { font-size:1.2em; }
</style>
<script type="text/javascript">
var lon = 5;
var lat = 40;
var zoom = 5;
var map;
var geocoder;
var markersLayer;
var add1 = "1600 Amphitheatre Pky, Mountain View, CA";
function init(){
var options = {projection: new OpenLayers.Projection("EPSG:900913"),
displayProjection: new OpenLayers.Projection("EPSG:4326")};
map = new OpenLayers.Map('map', options);
geocoder = new google.maps.Geocoder();
var gmap = new OpenLayers.Layer.Google("Google", {sphericalMercator:true});
markersLayer = new OpenLayers.Layer.Markers("Suchergebnis");
map.addLayers([gmap, markersLayer]);
map.addControl(new OpenLayers.Control.LayerSwitcher());
map.zoomToExtent(
new OpenLayers.Bounds(
68.774414, 11.381836, 123.662109, 34.628906
).transform(map.displayProjection, map.projection));
}
function search(){
//alert('search start');
var address = document.getElementById('address').value+",Kathmandu, Nepal";
//alert(address);
var geocode_url="http://maps.googleapis.com/maps/api/geocode/json?sensor=false&address="
//needs google api
var geocoder = new GClientGeocoder();
//geocoder.setBaseCountryCode('Nepal');
var location = geocoder.getLatLng(address,
function(point) {
if (!point) {
alert(address + " not found");
} else {
//alert("going to "+address);
var loc = new OpenLayers.LonLat(point.x,point.y);
map.setCenter(loc,3);
}
}
);
}
</script>
</head>
<body onload="init()">
<h1 id="title">OSM + Google Maps + KML Reprojection</h1>
<input id="address" type="textbox" value="Sydney, NSW">
<input type="button" value="Geocode" onclick="search()">
<div id="map" class="smallmap"></div>
<div id="docs"></div>
</body>
</html>