Google Maps searching issue with placemarks - javascript

I'm developing a web page with a Google Maps application and I'm having a little trouble with something. As it stands, the web page has a functional map (without any layers) and a search bar. I'm new to programming so hopefully there is a quick fix that I'm missing.
When I search an address, there is a placemark that is placed on the map. However, the map doesn't zoom into the placemark. How can I make the map zoom in for each searched address?
<script type="text/javascript">
var geocoder;
var map;
function initialize() {
geocoder = new google.maps.Geocoder ();
var latlng = new google.maps.LatLng (55.1667, -114.4000);
var myOptions = {
zoom: 5,
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);
}
});
}
</script>
Thank you

I would call two functions:
(1) center the map on the marker
Either you already have the LatLng, or obtain it from marker.getPosition(), with it call map.setCenter(myLatLng).
(2) Set the zoom of the map
map.setZoom(zoomLevel), could be fixed around 12 to 16, or variable depending what kind of marker it is (street address or city overview?) This information can be stored in the marker variable, marker.zoomLevel.
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 });
map.setZoom(16);
}
else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}

Related

Loading markers at intervals

In my project I have a google map, and I need to get markers on my map from database.
I have simple code like in 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.addListener(map, 'idle', function () {
getmarkers(map);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
This code works well, but it has one lack - it loads new markers only if user moves map.
But I need to load markers also if user is just sitting in front of computer and look on a map, not moving it.
I think the best way to do this is to use setInterval(getmarkers(map), 3000) but if I use it except where that function google.maps.event.addListener(... it can't find map. Are there any ways to solve this problem?
there are 2 issues,
setInterval expects the first argument to be a function(but it isn't, it's a function-call which will be executed immediately). Use a anonymous function to execute the statement:
setInterval(function(){getmarkers(map);}, 3000);
place the setInterval-call at the end of initialize to be sure that map is defined.

Google Maps API Does Not center the correct location

I have been through every possible question related to my problem and tried many solutions, none seem to help. I am using the Map API of Google and the map is not centering to the correct lat long pair. It is pointing at (0,0) which is some where in the middle of South Pacific Ocean. Upon doing geolocation of my Lat Long pairs, it give the correct address.
Here is my code:
$(document).ready(function(){
var loc = {lat:0,long:0};
if (navigator.geolocation){
navigator.geolocation.getCurrentPosition(showPosition);
}else{
alert("Geolocation is not supported by this browser.");
}
console.log(loc);
function showPosition(position){
loc.lat=position.coords.latitude;
loc.long=position.coords.longitude;
var geocoder = new google.maps.Geocoder();
var latLng = new google.maps.LatLng(loc.lat, loc.long);
console.log(latLng);
if (geocoder) {
geocoder.geocode({ 'latLng': latLng}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
console.log(results[0].formatted_address);
alert('Address:'+results[0].formatted_address);
}else {
console.log("Geocoding failed: " + status);
}
}); //geocoder.geocode()
}
}
var latLong = new google.maps.LatLng(loc.lat, loc.long);
var mapOptions = {
center: latLong,
useCurrentLocation : true,
zoom: 14,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var mapMsg = new google.maps.Map(document.getElementById("local_map"), mapOptions);
google.maps.event.addDomListener(window, 'load');
var markerOptions = new google.maps.Marker({
clickable: true,
flat: true,
map: mapMsg,
position: latLong,
title: "You are here",
visible:true,
icon:'http://maps.google.com/mapfiles/ms/icons/blue-dot.png',
});
});
Here is the screenshot of Firefox's console showing the correct Location address and lat long.
the First two Lines in the console are the Coordinates, the third line is the Geocoded location.
Please tell me where I'm wrong. I know this would be a silly mistake, but I'm new to it.
Regards
You never obtain the location from the geocoder result, or set the marker - and the order of execution is upside down (but does not fail)
Do this instead :
...
if (status == google.maps.GeocoderStatus.OK) {
var markerOptions = new google.maps.Marker({
clickable: true,
flat: true,
map: mapMsg,
position: results[0].geometry.location,
title: "You are here",
visible:true,
icon:'http://maps.google.com/mapfiles/ms/icons/blue-dot.png',
});
var marker = new google.maps.Marker(markerOptions);
mapMsg.setCenter(results[0].geometry.location);
} else {
console.log("Geocoding failed: " + status);
}
...
Here is a somehow cleaned / working version of your code http://jsfiddle.net/zqeCX/
But you should really consider using one of the google map examples as a starting point, to get the execution flow right.
This is because navigator.geolocation.getCurrentPosition is async.
Therefore, when you do var latLong = new google.maps.LatLng(loc.lat, loc.long); the loc.lat is still '0', as is loc.long.
So you need to include does lines in your function showPosition.

Google Maps API custom Icons with SSL

I have a Google Maps Application and I want to put custom Icons instead of the generic red icon that usually shows up. But no matter what I do I can not set a different icon it always shows up as the red one. I read that you can not have https in the url for icons so I uploaded it to an image host but I still can't get the icon to change. How do I get a custom icon on the map or do I have to go with bing?
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(-34.397, 150.644);
var mapOptions = {
zoom: 10,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
}
function codeAddress() {
initialize();
var address = document.getElementById("address").value;
range = document.getElementById("distance").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,
icon: "http://labs.google.com/ridefinder/images/mm_20_red.png"
position: results[0].geometry.location
});
lat1 = results[0].geometry.location.lat();
lng1 = results[0].geometry.location.lng();
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
load();
}
Notice where it says:
icon: "http://labs.google.com/ridefinder/images/mm_20_red.png"
Not matter what I change that too it always shows the red generic icon.
You can load marker images over both HTTP and HTTPS on your page. However, you will want to make sure that the scheme matches the containing page's scheme (or at least, make sure that you use HTTPS if the page does too).
It seems you have typo in your MarkerOptions object: a missing comma after the icon string.
var marker = new google.maps.Marker({
map: map,
icon: "http://labs.google.com/ridefinder/images/mm_20_red.png",
position: results[0].geometry.location
});

Google Map geocoder not as accurate as a Google maps

I have a database containing addresses that are accurate to building level. When I put these manually into Google Map's search, Google Maps finds them no problem - the markers appears right over the correct building. However, when I pass these same addresses to the Google Maps API geocoder using the below code, the markers show up only on the street and not the building.
How do I increase the accuracy?
HTML/PHP:
<div id="addressline"><?php echo theaddress(); ?></div>
JS:
function myGeocodeFirst() {
geocoder = new google.maps.Geocoder();
geocoder.geocode( {'address': document.getElementById("addressline").innerHTML},
function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
firstLoc = results[0].geometry.location;
map = new google.maps.Map(document.getElementById("map_canvas"),
{
center: firstLoc,
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
markers = new google.maps.Marker({
position: firstLoc,
map: map,
});
}
else {
document.getElementById("text_status").value = status;
}
}
);
}
window.onload=myGeocodeFirst;
Google Maps uses a number of different data sources to locate search results on the map.
The entry you are seeing that is "correct" is a Places database entry. See this page and enter you search string (St Clement’s Church, Edge Lane, Chorlton, M21 9JF).
The geocoder gets is designed to return coordinates for postal addresses, there is not enough information in your string for it to return accurate results:
http://www.geocodezip.com/v3_example_geo2.asp?addr1=St%20Clement%E2%80%99s%20Church,%20Edge%20Lane,%20Chorlton,%20M21%209JF&geocode=1
It looks like it is just returning the geocode for the postcode:
Manchester M21 9JF, UK (53.4414411, -2.285287100000005)
It does look like the geocoder does have that location in it. If I use "St Clement’s Church, Edge Lane", it seems to get the "rooftop" geocode (although it reports "APPROXIMATE")
http://www.geocodezip.com/v3_example_geo2.asp?addr1=St%20Clement%E2%80%99s%20Church,%20Edge%20Lane,%20Chorlton,%20M21%209JF&geocode=1&addr2=St%20Clement%E2%80%99s%20Church,%20Edge%20Lane&geocode=2
St Clement's Church, 6 Edge Ln, Manchester, Lancashire M21 9JF, UK (53.4406823, -2.283755499999984)
proof of concept fiddle
code snippet:
var geocoder, map, service, infowindow, bounds;
function initialize() {
map = new google.maps.Map(
document.getElementById("map_canvas"), {
center: new google.maps.LatLng(37.4419, -122.1419),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var request = {
query: "St Clement’s Church, Edge Lane, Chorlton, M21 9JF"
}
infowindow = new google.maps.InfoWindow();
service = new google.maps.places.PlacesService(map);
bounds = new google.maps.LatLngBounds();
service.textSearch(request, callback);
}
google.maps.event.addDomListener(window, "load", initialize);
function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
var place = results[i];
var marker = createMarker(results[i]);
bounds.extend(marker.getPosition())
}
map.fitBounds(bounds);
google.maps.event.trigger(marker, 'click');
}
}
function createMarker(place) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(place.name);
infowindow.open(map, this);
});
return marker;
}
html,
body,
#map_canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?libraries=places"></script>
<div id="map_canvas"></div>
Basically there is a name and an address. Google database can have other name for the same location. You can read my answer here: http://www.stackoverflow.com/questions/12788664/google-maps-api-geocode-returns-different-co-ordinates-then-google-maps/12790012#12790012. In the google response you need to loop through the placemark object to find the most similar location.

Noob question: How to get information if google map is loaded (initialized)

I am new with google maps api. I took some sample from the manual and trying to change it the way I need, so here is the what I am trying to do:
This is the example from google maps manual
var geocoder;
var map;
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng( 40.714353, -74.005973);
var myOptions = {
zoom: 10,
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);
}
});
}
I have changed codeAddress function a little and trying to call it on page load like this:
function codeAddress(address) {
//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);
}
});
}
codeAddress("Some Address");
But it give me a javascript error "geocoder is undefined". How can I make the script wait until the map is loaded and then run the codeAddress function? I don't want to path my address during initialization.
I hope this is clear
Thank you in advance.
The problem is that you're calling codeAddress directly after defining it (and hence this is before the initialise() method runs.
Consequently you need to run this later on some trigger. A quick and dirty way to do this is to set this as the body's onload event; this will wait until all resources (including images) have fully loaded, but that might not be too much of a problem given that the map is an image as well.
Alternatively, most JS frameworks will give you very convenient methods to fire your handlers at various points in the page's lifecycle. If you're using one of these, you may wish to investigate the options available to you and pick the best one, which depends on a number of factors.
Critically, don't forget that you must call initialise() before you call codeAddress()!

Categories