Error: 'google' is undefined - Map fails to load

57 views
Skip to first unread message

Rcdeveloper

unread,
Sep 21, 2015, 8:52:56 PM9/21/15
to Google Maps JavaScript API v3
Hi, 

I have a maps page that works correctly in my local machine, but when I have in a remote server(win 2008 server), it does not work correctly it shows an script error, 

 I try with 
<script src="http://maps.googleapis.com/maps/api/js?v=3&sensor=false&hl=es" type="text/javascript"></script> and is the same result, google is not defined
 <script src="https://maps.googleapis.com/maps/api/js?v=3&sensor=false&hl=es" type="text/javascript"></script>

This is my code:

<!DOCTYPE html>
<html>
 <head>
    <title>Mapa Oficinas de Farmacia</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> 
<style>
.etiqueta {
font-size: 9pt; 
font-family: 'Microsoft Sans Serif';
}
.valor {
width: 95%;
}
</style>
<script src="http://maps.googleapis.com/maps/api/js?v=3&sensor=false&hl=es" type="text/javascript"></script>
    <script type="text/javascript">
        var gmap;
        var myPano = null;
        var puntolatlon;
        var prmDir;
        var geocoder;
        var geoMarker;
        var prmLngX = null;
        var prmLatY = null;
        var prmYaw = null;
        var prmPitch = null;
        var prmZoom = null;
        var prmDir = null;

        var iconoFarmacia = {
            anchor: new google.maps.Point(8, 9),
            url: './iconos/iconoFarmacia.png',
            size: new google.maps.Size(16, 16)
        };

        google.maps.event.addDomListener(window, 'load', initialize);

        function initialize() 
        {
            var mapOptions = 
            {
                panControl: true,
                zoomControl: true,
                mapTypeControl: true,
                scaleControl: false,
                mapTypeId: google.maps.MapTypeId.ROADMAP,
                streetViewControl: true,
                overviewMapControl: true,
                overviewMapControlOptions: { opened: true }
            };

            gmap = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
            geocoder = new google.maps.Geocoder();

            //obtenemos los parametros que nos vienen en la URL
            URL = location.href;
            //longitud
            if ((URL).search('longitudX') != -1) { prmLngX = leeParametros('longitudX'); }

            //latitud
            if ((URL).search('latitudY') != -1) { prmLatY = leeParametros('latitudY'); }

            //yaw
            if ((URL).search('yaw') != -1) { prmYaw = leeParametros('yaw'); }

            //pitch
            if ((URL).search('pitch') != -1) { prmPitch = leeParametros('pitch'); }

            //zoom
            if ((URL).search('zoom') != -1) { prmZoom = leeParametros('zoom'); }

            //direccion
            if ((URL).search('direccion') != -1) 
            {
            prmDir = leeParametros('direccion');
            prmDir = unescape(prmDir);

                if (prmDir != "") {
                    document.getElementById('txtCalle').value = prmDir;
                }
            }
            else 
            {
                //una direccion por defecto
                prmDir = 'Conselleria de sanidade, San Lazaro, 15703 Santiago de Compostela';
                document.getElementById('txtCalle').value = prmDir;
            }
            if ( (prmLngX == null || prmLatY == null) && prmDir !=null )
            {
                // si no tenemos coordenadas obtenemos a partir de la direccion que viene en el parametro
                if (geocoder) 
                {
                    geocoder.geocode(
            {
            'address': prmDir, 
region: 'ES' 
},
            function(results, status) 
            {
               if (status == google.maps.GeocoderStatus.OK) 
               { var locResultado = results[0].geometry.location;
                   gmap.setCenter(locResultado);
                   gmap.setZoom(15);
                   addResultadoAMapa(locResultado);
                   inicializarTrasResultado(locResultado);
               }
               else 
               {
                alert(prmDir + ": dirección no encontrada: " + status);
               }
            }
            );
                }
            }
            else if (prmLngX != null && prmLatY != null)
            {
var puntoCoord = new google.maps.LatLng(prmLatY, prmLngX);
gmap.setCenter(puntoCoord);
gmap.setZoom(15);
                
                if (prmYaw == null || prmPitch == null || prmZoom == null) 
                {  //buscamos solo por coordenadas
                    addResultadoAMapa(puntoCoord);
                }
                else 
                {   //buscamos coordenas y yaw, pitch y zoom --> por todo
                    addResultadoAMapa(puntoCoord, prmYaw, prmPitch, prmZoom);
                }
                
inicializarTrasResultado(puntoCoord);
            }
else 
{
alert("Parámetros de búsqueda incompletos");
}            
        }


        function inicializarTrasResultado(puntoCoord) 
        {
            if (geoMarker) geoMarker.setMap(null);
            
            //ponemos una marca encima de las coordenadas en el mapa
            geoMarker = new google.maps.Marker({
                map: gmap,
                position: puntoCoord,
                icon: iconoFarmacia
            });

            //var streetViewLayer = new google.maps.StreetViewCoverageLayer();
            //streetViewLayer.setMap(gmap);
        }


function addResultadoAMapaGenerico(panoramaOptions, zoomAux) 
        {
            myPano = new google.maps.StreetViewPanorama(document.getElementById("streetviewpanoramadiv"), panoramaOptions);
            gmap.setStreetView(myPano);
            myPano.setVisible(true);

            var stvService = new google.maps.StreetViewService();
            stvService.getPanoramaByLocation(myPano.getPosition(), 50, disponibilidadStreetview);

            document.getElementById("txtLong").value = redond(myPano.getPosition().lng(), 6);
            document.getElementById("txtLat").value = redond(myPano.getPosition().lat(), 6);
            document.getElementById("txtZoom").value = redond(zoomAux, 0);
            document.getElementById("txtYaw").value = redond(myPano.getPov().heading, 6);
            document.getElementById("txtPitch").value = redond(myPano.getPov().pitch, 6);

            google.maps.event.addListener(myPano, "error", handleNoFlash);
            google.maps.event.addListener(myPano, "pov_changed", onPovChange);
            google.maps.event.addListener(myPano, "initialized", onNewLocation);
            google.maps.event.addListener(myPano, 'position_changed', onPositionChanged);
            google.maps.event.addListener(gmap.getStreetView(), 'visible_changed', onVisibilityChanged);
        }
        
        
        function addResultadoAMapa(puntoLatLon) 
        {
            var yaw = null;
            var pitch = null;
            var punto = puntoLatLon;

            var panoramaOptions = 
            {
                position: puntoLatLon,
                pov: {
                    heading: yaw,
                    pitch: pitch
                }
            };
            
            addResultadoAMapaGenerico(panoramaOptions, myPano.getZoom());
        }


        function addResultadoAMapa(puntolatlon, yaw, pitch, zoom) 
        {
            if (isNaN(yaw)) { yaw = 0; }
            if (isNaN(pitch)) { pitch = 0; }
            if (isNaN(zoom)) { zoom = 0; }
            
            var yawAux = yaw;
            var pitchAux = pitch;
            var zoomAux = zoom;
            var punto = puntolatlon;

            var panoramaOptions = {
                position: puntolatlon,
                pov: {
                    heading: redond(yawAux, 6),
                    pitch: redond(pitchAux, 6),
                    zoom: redond(zoomAux, 6)
                }
            };
            
            addResultadoAMapaGenerico(panoramaOptions, zoomAux);
        }


        function disponibilidadStreetview(result, status) 
        {
            if (status != google.maps.StreetViewStatus.OK) 
            {
                document.getElementById("txtError").value = " 'Streetview' no disponible en la ubicación.";
                document.getElementById("map_canvas").style.height = 580 + 'px';
                document.getElementById("streetviewpanoramadiv").style.height = 0 + 'px';
            }
        }


        function redond(num, ndec) {
            var fact = Math.pow(10, ndec);

            /* Se desplaza el punto decimal ndec posiciones, 
            se redondea el numero y se vuelve a colocar 
            el punto decimal en su sitio. */
            return Math.round(num * fact) / fact;
        }

        function handleNoFlash(errorCode) {
            document.getElementById("txtError").value = " 'Streetview' no disponible en la ubicación.";
            //mostramos el mapa mas grande ya que no hay streetview
            document.getElementById("map_canvas").style.height = 580 + 'px';
            document.getElementById("streetviewpanoramadiv").style.height = 0 + 'px';
        }

        function onPovChange() {
            document.getElementById("txtZoom").value = redond(myPano.getZoom(), 0);
            document.getElementById("txtYaw").value = redond(myPano.getPov().heading, 6);
            document.getElementById("txtPitch").value = redond(myPano.getPov().pitch, 6);
        }

        function onNewLocation(point) {
            //para que funcione correctamente debo intercambiar los valores
            document.getElementById("txtLong").value = redond(point.lng(), 6);
            document.getElementById("txtLat").value = redond(point.lat(), 6);
        }

        function onPositionChanged() {
            //para que funcione correctamente debo intercambiar los valores
            document.getElementById("txtLong").value = redond(myPano.getPosition().lng(), 6);
            document.getElementById("txtLat").value = redond(myPano.getPosition().lat(), 6);
            var stvService = new google.maps.StreetViewService();
            stvService.getPanoramaByLocation(myPano.getPosition(), 50, disponibilidadStreetview);
        }

        function onVisibilityChanged() 
        {
            if (this.getVisible() == false) 
            {
                document.getElementById("txtError").value = " 'Streetview' no disponible en la ubicación.";
                document.getElementById("map_canvas").style.height = 580 + 'px';
                document.getElementById("streetviewpanoramadiv").style.height = 0 + 'px';
                
                if (geoMarker) 
                {
                    document.getElementById("txtLong").value = redond(geoMarker.getPosition().lng(), 6);
                    document.getElementById("txtLat").value = redond(geoMarker.getPosition().lat(), 6);
                }
            }
            else 
            {
                document.getElementById("txtError").value = "";
                document.getElementById("map_canvas").style.height = 296 + 'px';
                document.getElementById("streetviewpanoramadiv").style.height = 288 + 'px';
            }
        }


        function hasErrorOccurred(error) 
        {
            if (error) 
            {
                alert("Error " + error.code + ": " + (error.message || (error.details && error.details.join(" ")) || "Unknown error"));
                return true;
            }
            
            return false;
        }

        //funcion que lee los parametros de la URL
        function leeParametros(name) 
        {
            name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
            var regexS = "[\\?&]" + name + "=([^&#]*)";
            var regex = new RegExp(regexS);
            var results = regex.exec(window.location.href);

            if (results == null)
                return "";
            else
            //necesario la funcion unescape porque algunos navegadores pintan los espacios como %20
                return unescape(results[1]);
        }
    </script> 
    
 </head>

 <body bgcolor="lightgrey">
   <form id="form1" runat="server" action="#">
    
    <div id="map_canvas" style="height: 296px; width: 100%;"></div>
    <br />
    
    <div id="streetviewpanoramadiv" style="height: 288px; width: 100%;"></div>
    <br /> 
        
    <fieldset style="width: 824px" align="center">
        <legend class="etiqueta">Datos Localización</legend> 
        <table>
            <tr>
                <td style="width: 95px"><label for="txtLong" ID="lblLon" class="etiqueta">Lon. (X):</label></td>
                <td style="width: 310px"><input type="text" ID="txtLong" class="valor" disabled /></td>

                <td style="width: 95px"><label for="txtLat" ID="lblLat" class="etiqueta">Lat. (Y):</label></td>
                <td style="width: 310px"><input type="text" ID="txtLat" class="valor" disabled /></td>
            </tr>
            <tr>
                <td style="width: 95px"><label for="txtYaw" ID="lblYaw" class="etiqueta">Yaw:</label></td>
                <td style="width: 310px"><input type="text" ID="txtYaw" class="valor" disabled /></td>

                <td style="width: 95px"><label for="txtPitch" ID="lblYaw" class="etiqueta">Pitch:</label></td>
                <td style="width: 310px"><input type="text" ID="txtPitch" class="valor" disabled /></td>
            </tr>
            <tr>
                <td style="width: 95px"><label for="txtZoom" ID="lblZoom" class="etiqueta">Zoom:</label></td>
                <td style="width: 310px"><input type="text" ID="txtZoom" class="valor" disabled /></td>

                <td style="width: 95px"><label for="txtError" ID="lblError" class="etiqueta">Descripción:</label></td>
                <td style="width: 310px"><input type="text" ID="txtError" class="valor" disabled /></td>
            </tr>
            <tr>
                <td style="width: 95px"><label for="txtCalle" ID="lblCalle" class="etiqueta">Ubicación:</label></td>
                <td colspan="3" ><input type="text" ID="txtCalle"  disabled style="width: 706px; text-transform :uppercase"/></td>
            </tr>
            <tr>
                <td style="width: 95px"></td>
                <td style="width: 310px"></td>
                <td style="width: 90px"></td>
                <td style="width: 310px" align="right"></td>
            </tr>
        </table>
    </fieldset>
    
   </form>
 </body>
</html>

Reply all
Reply to author
Forward
0 new messages