OpenLayers: Geocoding Data Google + OSM - google-maps-markers

I got this error TypeError: placemarks is undefined I use google api and openlayer api .
help me this. I am using google api v3 and openLayer map i want to give address in textbox and click button and the geocoding perform.
In my code I got this error TypeError: placemarks is undefined Here is my full code
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>OpenLayers: Geocoding Data Google + OSM</title>
<link rel="stylesheet" href="../theme/default/style.css" type="text/css" />
<link rel="stylesheet" href="style.css" type="text/css" />
<script type="text/javascript" src="//maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&key=AIzaSyBz7CjlxpWO8HgM_ATuq3_F85wfAoupXck&language=de"></script>
<script src="OpenLayers.js"></script>
<script src="http://www.openstreetmap.org/openlayers/OpenStreetMap.js" type="text/javascript"></script>
<style type="text/css">
#map {
width: 100%;
height: 80%;
border: 1px solid black;
}
</style>
<script type="text/javascript">
var map, vectors, geocoder;
// Define marker style
// #fixme: where can we get information about these marker styles
var markerStyle = {
externalGraphic : 'img/marker.png',
pointRadius : 12
};
function init() {
// Add the map
var options = {
projection : new OpenLayers.Projection("EPSG:900913"),
displayProjection : new OpenLayers.Projection("EPSG:4326"),
units : "m",
maxResolution : 156543.0339,
maxExtent : new OpenLayers.Bounds(-20037508.34, -20037508.34, 20037508.34, 20037508.34)
};
map = new OpenLayers.Map('map', options);
// Add the OpenStreetMaps Layer
var osm = new OpenLayers.Layer.OSM.Mapnik("OpenStreetMap (Mapnik)", {
displayOutsideMaxExtent : true,
wrapDateLine : true,
buffer : 0
});
map.addLayer(osm);
// Add the google maps Layer
var gmap = new OpenLayers.Layer.Google("Google", {
sphericalMercator : true
});
map.addLayer(gmap);
// Add a vector Layer which holds the markers
vectors = new OpenLayers.Layer.Vector("Vector Layer");
map.addLayer(vectors);
// Allow marker drag
var dragCtl = new OpenLayers.Control.DragFeature(vectors);
dragCtl.onComplete = function(feature, position) {
var ll = map.getLonLatFromPixel(position);
var coords = ll.transform(map.getProjectionObject(), new OpenLayers.Projection("EPSG:4326"));
alert('New coordinates: ' + coords.lon + ' ' + coords.lat);
}
map.addControl(dragCtl);
dragCtl.activate();
map.addControl(new OpenLayers.Control.LayerSwitcher());
// Center map
var centerLonLat = new OpenLayers.LonLat(10.5, 51.6).transform(new OpenLayers.Projection("EPSG:4326"), map.getProjectionObject());
map.setCenter(centerLonLat, 5);
}
function codeAddress() {
var address = document.getElementById('address').value;
geocoder = new google.maps.Geocoder();
geocoder.geocode({
'address' : address
}, gotGeocodes);
alert("hiiii");
}
function gotGeocodes(response) {
// Clear markers from vector layer
alert("hi");
vectors.destroyFeatures();
if (typeof response.location !== 'undefined') {
alert("Sorry, we were unable to geocode that address");
} else {
var placemarks = response.Placemark;
// We may get more than one result here. So you can display
// all results or just the first like here
if (placemarks.length > 0) {
var coords = placemarks[0].Point.coordinates;
var ll = new OpenLayers.LonLat(coords[0], coords[1]).transform(new OpenLayers.Projection("EPSG:4326"), map.getProjectionObject());
var pointGeometry = new OpenLayers.Geometry.Point(ll.lon, ll.lat);
var point = new OpenLayers.Feature.Vector(pointGeometry, null, markerStyle);
vectors.addFeatures([point]);
map.setCenter(ll, 16);
}
}
}
</script>
</head>
<body onload="init();">
<h1 id="title">Get geocoding data from google</h1>
<p id="shortdesc">
Get geocoding data from google an show it in openstreetmap or google maps.
</p>
<form action="#" onsubmit="codeAddress(); return false;">
<strong>Enter an address:</strong>
<input type="text" id="address" name="q" value="" size="40" />
<input type="submit" name="find" value="Search" />
</form>
<div id="map"></div>
</body>
</html>

Related

i need to hide a dynamically created div using dynamically created button using jquery constructor function

<!DOCTYPE html>
<html>
<head>
<script src='jquery-1.11.2.js' type="text/javascript"></script>
<div id='divn'></div>
<script>
function createDomControls(id,appendToId)
{ this.id=id;
this.appendToId=appendToId;
this.divTag=function(divId,className,style,appendToId)
{
//var divId = "div" + Math.floor((Math.random() * 100000) + 1);
$('<div/>', {
id: divId,
style: style,
class:className
}).appendTo('#' + appendToId);
}
this.buttonTag=function(type,id,value,appendToId)
{
$('<input/>',{
type:type,
id:id,
value:value,
onclick:onclick function(){
$('#div1').hide();
}
});
}
}
var domControls=new createDomControls('divm','divn');
var div=domControls.divTag('div1','cls','background:pink;width:500px;height:670px;padding:12px;margin:0px;','divn');
var btn=domControls.buttonTag('button','btn1','+','div1');
</script>
</head>

Google Maps current location JavaScript error

I want to get my current location using Google Maps Geolocation by Latitude and Longitude and I also want to set the origin as my current location but I'm not getting the current location. What should I do?
This is my code:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Draggable directions</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&signed_in=true"></script>
<script>
var rendererOptions = {
draggable: true
};
var directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);
var directionsService = new google.maps.DirectionsService();
var map;
function initialize() {
var lat, lon, mapOptions;
if(navigator.geolocation){
navigator.geolocation.getCurrentPosition(
function(position){
lat = position.coords.latitude;
lon = position.coords.longitude;
mapOptions = {
zoom: 7,
center: new google.maps.LatLng(lat, lon),
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById('directionsPanel'));
google.maps.event.addListener(directionsDisplay, 'directions_changed', function() {
computeTotalDistance(directionsDisplay.getDirections());
});
calcRoute();
},
function(error){
alert('ouch');
});
}
else {
alert("Your browser doesn't support geolocations, please consider downloading Google Chrome");
}
}
function calcRoute() {
var request = {
origin: new google.maps.LatLng(lat, lon),
destination: new google.maps.LatLng(10.5200,76.2100),
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
function computeTotalDistance(result) {
var total = 0;
var myroute = result.routes[0];
for (var i = 0; i < myroute.legs.length; i++) {
total += myroute.legs[i].distance.value;
}
total = total / 1000.0;
document.getElementById('total').innerHTML = total + ' km';
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas" style="float:left;width:70%; height:100%"></div>
<div id="directionsPanel" style="float:right;width:30%;height 100%">
<p>Total Distance: <span id="total"></span></p>
</div>
</body>
</html>

JVectorMap - Selecting a Region Using a Button

I am using J Vector Map (http://jvectormap.com/documentation/javascript-api/) to create a map of the United States.
What I want to be able to do is have a button for each state that you can click on and have the corresponding region in the map be selected (or unselected, if it already was selected). I am trying to use map.setSelectedRegion for this, but I can't get any of the code to work. Currently trying map.setSelectedRegion("US-CA") to no avail.
Any ideas on what to do?
Thanks!
There seem to be a lot of request for linking links with jvectormap.
I've put together a jsfiddle here: http://jsfiddle.net/3xZ28/117/
HTML
<ul id="countries">
<li>Romania</li>
<li>Australia</li>
</ul>
<div id="world-map" style="width: 600px; height: 400px"></div>
JS
var wrld = {
map: 'world_mill_en',
regionStyle: {
hover: {
"fill": 'red'
}
}
};
function findRegion(robj, rname) {
var code = '';
$.each(robj, function (key) {
if ( unescape(encodeURIComponent(robj[key].config.name)) === unescape(encodeURIComponent(rname)) ) {
code = key;
};
});
return code;
};
$(document).ready(function () {
$('#world-map').vectorMap(wrld);
var mapObj = $('#world-map').vectorMap('get', 'mapObject');
$('#countries').on('mouseover mouseout', 'a:first-child', function (event) {
// event.preventDefault();
var elem = event.target,
evtype = event.type,
cntrycode = findRegion(mapObj.regions, $(elem).text());
if (evtype === 'mouseover') {
mapObj.regions[cntrycode].element.setHovered(true);
} else {
mapObj.regions[cntrycode].element.setHovered(false);
};
});
});
Once you've set the handle
var mapObject = $('#your_map_div_id').vectorMap('get', 'mapObject');
Just use the built in function setSelectedRegions (mind the "s"):
mapObject.setSelectedRegions(your_region_code); //to set
mapObject.setSelectedRegions({your_region_code:false}); //to unset
If it still doesn't work, post your code, maybe it's something else.
This code is outdated, below is updated version of the code, according jvectormap latest API. Here is demo snippet:
<!DOCTYPE html>
<html>
<head>
<title>jVectorMap demo</title>
<link rel="stylesheet" href="jqvmap.min.css" type="text/css" media="screen"/>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script src="jquery.vmap.min.js"></script>
<script src="jquery.vmap.world.js"></script>
<script>
jQuery(document).ready(function () {
$('#vmap').vectorMap({
map: 'world_en',
backgroundColor: '#2f95c9',
color: '#ffffff',
hoverOpacity: 0.7,
selectedColor: '#666666',
enableZoom: true,
showTooltip: true,
scaleColors: ['#C8EEFF', '#006491'],
normalizeFunction: 'polynomial',
regionsSelectableOne: false,
regionsSelectable: false,
series: {
regions: [{
scale: ['#C8EEFF', '#0071A4'],
normalizeFunction: 'polynomial'
}]
}
});
var mapObj = $('#vmap').data('mapObject');
$('#countries').on('mouseover mouseout', 'a:first-child', function (event) {
// event.preventDefault();
var elem = event.target,
evtype = event.type;
if (evtype === 'mouseover') {
mapObj.select($(elem).attr('id'));
} else {
mapObj.deselect($(elem).attr('id'));
};
});
});
</script>
</head>
<body>
<ul id="countries">
<li><a id="RO" href="">Romania</a></li>
<li><a id="AU" href="">Australia</a></li>
</ul>
<div id="vmap" style="width: 100vw; height: 100vh;"></div>
</body>
</html>

Get West/East | North/South from GPS coordinates from Google API

I have Lat & Long. How can i get West/East | North/South from GPS?
Screenshot attached: ScreenShot
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript" src="/design/js/jquery-autocomplete/jquery.autocomplete_geomod.js"></script>
<script type="text/javascript" src="/design/js/jquery-autocomplete/geo_autocomplete.js"></script>
<link rel="stylesheet" type="text/css" href="/design/js/jquery-autocomplete/jquery.autocomplete.css" />
<script type="text/javascript">
$().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);
// use all the autocomplete options as documented at http://docs.jquery.com/Plugins/Autocomplete
/* additional geo_autocomplete options:
mapkey : 'ABQ...' (required for Static Maps thumbnails, obtain a key for your site from http://code.google.com/apis/maps/signup.html)
mapwidth : 100
mapheight : 100
maptype : 'terrain' (see http://code.google.com/apis/maps/documentation/staticmaps/#MapTypes)
mapsensor : true or false
*/
$('#location').geo_autocomplete(new google.maps.Geocoder, {
mapkey: 'ABQIAAAAbnvDoAoYOSW2iqoXiGTpYBTIx7cuHpcaq3fYV4NM0BaZl8OxDxS9pQpgJkMv0RxjVl6cDGhDNERjaQ',
selectFirst: false,
minChars: 3,
cacheLength: 50,
width: 300,
scroll: true,
scrollHeight: 330
}).result(function(_event, _data) {
var coords = new google.maps.LatLng(
_data.geometry.location.lat(),
_data.geometry.location.lng()
);
$('#lat').val (_data.geometry.location.lat())
$('#lng').val (_data.geometry.location.lng())
console.log (coords.lat () + '/' + coords.lng ());
if (_data) map.fitBounds(_data.geometry.viewport);
});
});
</script>
<style>
.ac_results li img {
float: left;
margin-right: 5px;
}
</style>
<h3>jQuery geo-autocomplete Plugin Demo</h3>
<div>Location: <input type="text" id="location" /> (autocomplete)</div>
<br/>
<div id="coords">Lat:
<input id="lat" name="lat" />
Lng:
<input id="lng" name="lng" />
</div>
<br/>
East/West: if longitude < 0 then West, else East
North/South: if latitude < 0 then South else North
Explanation:
The 0-Meridian (through London/Greenwich) is the limit between west and east.
The Aequator is the limit between south and north.
in Google, coordinates are represented in decimal degrees, where the negative sign, defines E/W or N/S

Adding Multiple Markers to Google Maps v3 from JSON

I've been trying to make a web app that shows multiple markers on google maps. I tried using this tutorial and the code works fine until I get to the point where I need to get the JSON data from the server instead of using the example JSON data in the same js file as the code.
I try to save the ajax response into variable but i get this error
TypeError: json is null
[Break On This Error]
for (var i = 0, length = json.length; i < length; i++) {
And this is the code I am using.
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0; padding: 0 }
#map-canvas { height: 100% }
</style>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true"></script>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://code.jquery.com/jquery-migrate-1.1.1.min.js"></script>
</script>
<script type="text/javascript">
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(57.9, 14.6),
zoom: 5,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map-canvas"),
mapOptions);
var json = (function () {
var json = null;
$.ajax({
'async': false,
'global': false,
'url': "http://myurl.com/getdata",
'dataType': "json",
'success': function (data) {
json = data; } });
return json;})();
for (var i = 0, length = json.length; i < length; i++) {
var data = json[i],
latLng = new google.maps.LatLng(data.lat, data.lng);
// Creating a marker and putting it on the map
var marker = new google.maps.Marker({
position: latLng,
map: map,
title: data.title
});
}
var infoWindow = new google.maps.InfoWindow();
// Attaching a click event to the current marker
google.maps.event.addListener(marker, "click", function(e) {
infoWindow.setContent(data.description);
infoWindow.open(map, marker);
});
// Creating a closure to retain the correct data
//Note how I pass the current data in the loop into the closure (marker, data)
(function(marker, data) {
// Attaching a click event to the current marker
google.maps.event.addListener(marker, "click", function(e) {
infoWindow.setContent(data.description);
infoWindow.open(map, marker);
});
})(marker, data);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas"/>
</body>
</html>

Resources